⚡ Kotlin Fundamentals
Functions & Lambdas
Named functions, default params, extension functions, trailing lambdas.

Defining Functions

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

// Default parameters — avoid overloads
fun greet(name: String, prefix: String = "Hello") =
    "$prefix, $name!"

greet("Alice")           // "Hello, Alice!"
greet("Bob", "Hey")      // "Hey, Bob!"

// Named arguments improve readability
greet(name = "Carol", prefix = "Good morning")

Extension Functions

kotlin
// Add methods to existing classes — no inheritance needed
fun String.toTitleCase(): String =
    split(" ").joinToString(" ") { it.replaceFirstChar(Char::titlecase) }

"hello world".toTitleCase()  // "Hello World"

// Android-flavoured extension
fun View.hide() { visibility = View.GONE }
fun View.show() { visibility = View.VISIBLE }

Lambdas

kotlin
val double: (Int) -> Int = { x -> x * 2 }

fun runTwice(action: () -> Unit) { action(); action() }
runTwice { println("Beep") }   // trailing lambda syntax

listOf(1, 2, 3).forEach { println(it * 2) }

Key Takeaways

Default parameters reduce function overloads dramatically
Extension functions add methods to any class — ideal for View helpers
Lambdas are first-class values and can be stored and passed around
Trailing lambda syntax keeps call sites clean and readable
Lesson 7 of 30Kotlin Fundamentals
← Previous Next Lesson →