Lesson 2 Functions
Lesson 2 Functions
Functions
IntelliJ IDEA runs the program, and displays the results in the console.
Select Run > Edit Configurations to open the Run/Debug Configurations window.
⇒ 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 Apache 2 license.
Apache 2 license
fun printHello() {
println("Hello World")
}
printHello()
If a function does not return any useful value, its return type is Unit.
is equivalent to:
● Default parameters
● Required parameters
● Named arguments
Required parameters
It's considered good style to put default arguments after positional arguments,
that way callers only have to specify the required arguments.
The body of the code calls the function that was passed as the second argument,
and passes the first argument along to it.
The :: operator lets Kotlin know that you are passing the function reference as an
argument, and not trying to call the function.
Kotlin prefers that any parameter that takes a function is the last parameter.
You can pass a lambda as a function parameter without putting it inside the
parentheses.
Many Kotlin built-in functions are defined using last parameter call syntax.
repeat(3) {
println("Hello")
}
bright
red red-orange dark red orange saffron
orange
Filter iterates through a collection, where it is the value of the element during the
iteration. This is equivalent to:
The filter condition in curly braces {} tests each item as the filter loops through.
If the expression returns true, the item is included.
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.
Sequences are data structures that use lazy evaluation, and can be used with
filters to make them lazy.
⇒ filtered: kotlin.sequences.FilteringSequence@386cc1c4