Reading — step 1 of 5
Learn
~1 min readFunctions and Lambdas
Functions use fun. Parameter types are required; return type goes after :. Type can be inferred for single-expression functions.
fun add(a: Int, b: Int): Int {
return a + b
}
// Single-expression form:
fun multiply(a: Int, b: Int) = a * b // return type inferred as Int
Default arguments and named arguments make signatures very flexible:
fun greet(name: String, greeting: String = "Hello") = "$greeting, $name!"
greet("Alice") // Hello, Alice!
greet("Bob", greeting = "Howdy") // Howdy, Bob!
greet(name = "Carol") // Hello, Carol!
Vararg with vararg:
fun sum(vararg nums: Int) = nums.sum()
sum(1, 2, 3, 4) // 10
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…