Kotlin Basics: Variables, Control Flow, Functions, and Extensions

This article introduces Kotlin fundamentals for developers, covering variable declarations, control flow statements such as if, when, and loops, smart type inference, null-safety, function definitions with default parameters, varargs, extension functions, and provides practical code examples to help newcomers quickly adopt Kotlin.

Hujiang Technology
Hujiang Technology
Hujiang Technology
Kotlin Basics: Variables, Control Flow, Functions, and Extensions

2.1 Variables

Example program demonstrates variable and constant declarations using var and val, type inference, and string interpolation.

fun main(args: Array<String>) {
    var quantity = 5
    val price: Double = 20.3
    val name: String = "大米"
    println("单价:$price")
    println("数量:$quantity")
    println("产品:$name 总计:${quantity * price}")
}

Explanation of var vs val and type inference.

2.2 Statements

2.2.1 Using the in keyword

Shows how to check if a value lies within a range or collection using in and !in, with examples of if and for loops.

if (x in 1..y-1) print("OK")
if (x !in 0..array.lastIndex) print("Out")
for (x in 1..5) print(x)
for (name in names) println(name)
if (text in names) print("yes")

2.2.2 when expression

Provides a Kotlin equivalent of Java's switch, matching on values, types, and default case.

fun cases(obj: Any) {
    when (obj) {
        1 -> print("第一项")
        "hello" -> print("这个是字符串hello")
        is Long -> print("这是一个Long类型数据")
        !is String -> print("这不是String类型的数据")
        else -> print("else类似于Java中的default")
    }
}

2.2.3 Smart type inference

Demonstrates using is to check an object's type and let the compiler treat it as that type within the block.

fun getStringLength(obj: Any): Int? {
    if (obj is String) {
        return obj.length
    }
    return null
}

2.2.4 Null‑safety

Kotlin's safe‑call operator ?. and Elvis operator ?: are shown for handling nullable values.

data?.let { /* ... */ }
data ?: let { /* ... */ }

2.3 Functions

2.3.1 Function declaration

Functions are declared with fun. Simple examples of returning a string and a concise single‑expression form are provided.

fun say(str: String): String { return str }
fun say(str: String): String = str
fun getIntValue(value: Int) = value

2.3.2 Default parameters

Shows how default arguments can replace overloads.

fun say(str: String = "hello"): String = str

2.3.3 Vararg functions

Kotlin uses vararg for variable‑length arguments, analogous to Java's ellipsis.

fun hasEmpty(vararg strArray: String?): Boolean {
    for (str in strArray) {
        if ("" .equals(str) || str == null) return true
    }
    return false
}

2.3.4 Extension functions

Extension functions add new methods to existing classes, e.g., a toast helper for Android Activity.

fun Activity.toast(message: CharSequence, duration: Int = Toast.LENGTH_SHORT) {
    Toast.makeText(this, message, duration).show()
}

2.3.5 Passing functions as parameters

Illustrates higher‑order functions by passing a lambda to a lock utility.

fun <T> lock(lock: Lock, body: () -> T): T {
    lock.lock()
    try { return body() } finally { lock.unlock() }
}

2.4 Summary

A final composite example combines the concepts covered: variable declarations, nullable handling, vararg functions, and string interpolation.

fun main(args: Array<String>) {
    val firstName: String = "Tao"
    val lastName: String? = "Zhang"
    println("my name is ${getName(firstName, lastName)}")
}

fun hasEmpty(vararg strArray: String?): Boolean {
    for (str in strArray) {
        str ?: return true
    }
    return false
}

fun getName(firstName: String?, lastName: String? = "unknow"): String {
    if (hasEmpty(firstName, lastName)) {
        lastName?.let { return "${checkName(firstName)} $lastName" }
        firstName?.let { return "$firstName ${checkName(lastName)}" }
    }
    return "$firstName $lastName"
}

fun checkName(name: String?): String = name ?: "unknow"
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Mobile DevelopmentAndroidprogrammingKotlinFunctionsvariables
Hujiang Technology
Written by

Hujiang Technology

We focus on the real-world challenges developers face, delivering authentic, practical content and a direct platform for technical networking among developers.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.