functions

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

Single expression functions need no braces The return type can be inferred

Defaults

fun greet(name: String, greeting: String = "Hello") = "$greeting, $name"

Default parameters reduce overload bloat Named arguments make calls readable

Lambdas

val double = { n: Int -> n * 2 }
val evens = numbers.filter { it % 2 == 0 }

it is the implicit single parameter Use named parameters when the lambda grows beyond one line

Extension functions

fun String.isPort(): Boolean = toIntOrNull()?.let { it in 1..65535 } ?: false

Extension functions add methods to existing types They are resolved statically, not by inheritance That keeps them safe and predictable

Higher order

Functions can take functions That is where Kotlin stops being Java with less typing A filter, a map, a reduce are all functions of functions

Next

Classes in 06 classes

Test this in your lab first

Posted