Kotlin Tutorial menu

Kotlin Functions and Lambdas

A function is a named block of code that does one job. You write it once and use it many times.

Creating a Function

Use the fun keyword, a name, round brackets and curly braces:

Example

kotlin
fun greet() {
    println("Welcome to Workownix!")
}

fun main() {
    greet()
    greet()
}
Output
Welcome to Workownix!
Welcome to Workownix!

Parameters and Return Values

Parameters are inputs. Each one needs a name and a type. If the function gives back a value, write its type after the brackets.

Example

kotlin
fun total(price: Int, quantity: Int): Int {
    return price * quantity
}

fun main() {
    val bill = total(120, 3)
    println("Bill: Rs $bill")
    println("Bill: Rs ${total(50, 10)}")
}
Output
Bill: Rs 360
Bill: Rs 500

A function that returns nothing has the type Unit. You do not need to write it.

Single-Expression Functions

When a function only returns one expression, you can write it on one line with =:

Example

kotlin
fun square(n: Int) = n * n
fun isAdult(age: Int) = age >= 18

fun main() {
    println(square(7))
    println(isAdult(16))
}
Output
49
false

Default and Named Arguments

A parameter can have a default value. If the caller does not give that argument, the default is used. You can also write argument names when calling, which makes the call easy to read.

Example

kotlin
fun orderTea(cups: Int = 1, sugar: Boolean = true) {
    val type = if (sugar) "with sugar" else "without sugar"
    println("$cups cup(s) of tea $type")
}

fun main() {
    orderTea()
    orderTea(3)
    orderTea(sugar = false)
    orderTea(cups = 2, sugar = false)
}
Output
1 cup(s) of tea with sugar
3 cup(s) of tea with sugar
1 cup(s) of tea without sugar
2 cup(s) of tea without sugar

Lambdas

A lambda is a small function without a name, written inside curly braces. You can store it in a variable:

Example

kotlin
fun main() {
    val double = { n: Int -> n * 2 }
    println(double(21))
}
Output
42

Lambdas are most useful with collection functions. When a lambda has one parameter, you can call it it:

Example

kotlin
fun main() {
    val numbers = listOf(1, 2, 3, 4, 5, 6)
    val evens = numbers.filter { it % 2 == 0 }
    val squares = numbers.map { it * it }
    println(evens)
    println(squares)
    println(numbers.count { it > 3 })
}
Output
[2, 4, 6]
[1, 4, 9, 16, 25, 36]
3
FunctionWhat it does
filter { }Keeps items where the lambda is true
map { }Changes each item and makes a new list
count { }Counts items where the lambda is true
forEach { }Runs the lambda for each item
sortedBy { }Sorts by the value the lambda gives

Android code uses lambdas everywhere, for example to say what happens when a button is clicked. Practise them well.

Exercise

Exercise

What does listOf(3, 8, 5, 10).filter { it > 4 } return?

Learn Kotlin with a teacher

Join the App Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp