Functions are the building blocks of any Kotlin program. You've already seen fun main() โ now let's learn how to create your own.
Declaring a function
Use the fun keyword, followed by the name, parentheses, and the body in curly braces.
fun greet() {
println("Hello!")
}
fun main() {
greet()
greet()
}
You call a function by its name followed by parentheses.
Try it Yourself โReturn types
If a function returns a value, specify its type after :.
fun add(a: Int, b: Int): Int {
return a + b
}
fun main() {
val result = add(3, 7)
println(result)
}
The return keyword gives back a value to the caller.
Unit return type
When a function doesn't return a meaningful value, its return type is Unit โ just like void in Java. You can omit it.
fun sayHello(name: String): Unit {
println("Hello, $name!")
}
fun main() {
sayHello("Kotlin")
}
In practice, you rarely write : Unit. Kotlin assumes it when there's no return type declared.
Single-expression functions
For a function that's just one expression, skip the curly braces and use =.
fun square(x: Int) = x * x
fun main() {
println(square(5))
}
Kotlin infers the return type automatically. This is concise and elegant.
Try it Yourself โ