Lesson 2 Functions
Lesson 2 Functions
Functions
IntelliJ IDEA runs the program, and displays the results in the console.
⇒ Hello, Kotlin!
val temperature = 20
val isHot = if (temperature > 40) true else false
println(isHot)
⇒ false
⇒ This is an expression
kotlin.Unit
15
This work is licensed under the
Android Development with Kotlin Apache 2 license.
Parts of a function
fun printHello() {
println("Hello World")
}
printHello()
If a function does not return any useful value, its return type is Unit.
is equivalent to:
fun printHello(name: String?) {
println("Hi there!")
}
Parameter and
type Function
var dirtLevel = 20
arrow
val waterFilter = {level: Int -> level / 2}
println(waterFilter(dirtLevel))
⇒ 10
Code to
execute
The :: operator lets Kotlin know that you are passing the function
reference as an argument, and not trying to call the function.
Many Kotlin built-in functions are defined using last parameter call
syntax.
inline fun repeat(times: Int, action: (Int) -> Unit)
repeat(3) {
println("Hello")
}
bright
red red-orange dark red orange saffron
orange
Apply filter() on
list
Condition: element contains
“red”
red red-orange dark red
The filter condition in curly braces {} tests each item as the filter loops
through. If the expression returns true, the item is included.
⇒ [biology, birds]
Lazy evaluation of lists is useful if you don't need the entire result, or if
the list is exceptionally large and multiple copies wouldn't wouldn't fit
into RAM.
Filters are eager by default. A new list is created each time you use a
filter.