Magic Boxes, Functions
In Kotlin, functions start with the fun word fun.
Create a function
fun sayHello() {
println("Hello!")
}
fun main() {
sayHello() // use it
}
Ingredients and results
When you pass ingredients into a function, you put them in ( ),
and you also tell Kotlin the output type.
fun add(a: Int, b: Int): Int {
return a + b
}
fun main() {
val result = add(10, 20)
println(result)
}
Translation:
Define a fun magic box called add (ingredients are numbers a and b): (output will be a number) {
return a + b
}
One-line magic
If a function is simple, Kotlin lets you write it in one line.
fun multiply(a: Int, b: Int) = a * b
Short and sweet. That is why Kotlin developers can handle complex tasks with joy.