KT Kotlin

Kotlin: Functions & Extensions

What you will learn

Kotlin's concise function syntax, single-expression functions, default parameters, and extension functions — a powerful way to add methods to existing classes.

Basic function

fun greet(name: String): String {
    return "Hello, $name!"
}

Syntax: fun keyword, function name, parameters with types, : return type, body in { }. String interpolation with $ is built-in.

Single-expression functions

When a function has only one expression, omit the braces and use =:

fun double(x: Int): Int = x * 2
fun greet(name: String) = "Hello, $name!"

The return type can be inferred — no need to write : Int.

Default and named parameters

fun power(base: Int, exp: Int = 2) = base.pow(exp)

power(3)           // 9 (exp defaults to 2)
power(3, 3)        // 27
power(exp = 3, base = 2)  // 8 (named arguments, any order)

Named arguments let you skip some defaults and reorder parameters — very useful for functions with many parameters.

Extension functions

Add a method to a class without modifying it:

// Add .isEmail() to String
fun String.isEmail(): Boolean = this.contains("@")

"[email protected]".isEmail()  // true
"hello".isEmail()               // false

Extensions are static in nature — they don't actually modify the class; they're syntactic sugar for a static utility function.

Common mistakes

  • Forgetting that extension functions are not truly part of the class — they can be shadowed by member functions with the same signature
  • Using return inside a single-expression function (unnecessary — the expression is already the result)
  • Confusing = single-expression syntax with a lambda — they're different things

Quick check below!