iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Functions

Kotlin functions are first-class with default args, named args, varargs, single-expression bodies, extension functions, and infix syntax. The result feels DSL-y without being mysterious.

Real Kotlin function shapes

EXAMPLE
// 1) Named + default args — kill the “positional argument” soup
fun greet(name: String, prefix: String = "Hi", suffix: String = "!"): String =
    "$prefix, $name$suffix"

greet("Ada")                                     // 'Hi, Ada!'
greet(name = "Bo", suffix = ".")                 // 'Hi, Bo.'

// 2) Single-expression — return type inferred
fun add(a: Int, b: Int) = a + b
fun even(n: Int) = n % 2 == 0

// 3) Varargs + spread
fun total(vararg xs: Int) = xs.sum()
val ns = intArrayOf(1, 2, 3)
total(*ns)                                        // 6

// 4) Multiple returns — Pair / Triple / data class
fun divmod(a: Int, b: Int): Pair<Int, Int> = (a / b) to (a % b)
val (q, r) = divmod(17, 5)

// 5) Extension functions — add methods without inheritance
fun String.isEmail() = matches(Regex("\\S+@\\S+\\.\\S+"))
fun List<Int>.average2() = sum().toDouble() / size

"ada@example.com".isEmail()                       // true
listOf(1, 2, 3, 4).average2()                     // 2.5

// 6) Higher-order functions — pass functions in / out
fun retry(times: Int = 3, block: () -> String): String {
    repeat(times - 1) {
        try { return block() }
        catch (e: Exception) { /* try again */ }
    }
    return block()
}

val result = retry(times = 5) {
    httpGet("https://api.example.com")
}

// 7) Inline functions — zero-overhead higher-order calls
inline fun measure(block: () -> Unit): Long {
    val start = System.nanoTime()
    block()
    return System.nanoTime() - start
}

val ns2 = measure { heavyWork() }

// 8) Infix — makes DSLs read naturally
infix fun Int.times(action: () -> Unit) {
    for (i in 0 until this) action()
}

3 times { println("hi") }

Why it matters

Extension functions + named args + single-expression bodies are why Kotlin code reads so cleanly. The whole language nudges you towards small, named, composable pieces.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
fun add(a: Int, b: Int) = a + b           // single-expression
fun greet(name: String = "world") = "hi, $name"
fun divmod(a: Int, b: Int): Pair<Int, Int> = a/b to a%b
Try it Yourself »

Exercise

Single-expression function syntax.

fun add(a: Int, b: Int) a + b

Discussion

Loading…