Skip to content
skotch
...

Functions

fun greet(name: String): String {
return "Hello, $name!"
}
fun main() {
println(greet("world"))
}

Parameters require explicit type annotations. The return type can be omitted for Unit-returning functions.

Functions with a single expression can use = instead of a block:

fun square(n: Int): Int = n * n
fun isPositive(n: Int): Boolean = n > 0

Add methods to existing types:

fun Int.isEven(): Boolean = this % 2 == 0
fun String.shout(): String = this + "!"
fun main() {
println(42.isEven()) // true
println("hello".shout()) // hello!
}

Inside an extension function, this refers to the receiver object.

Functions can be defined inside other functions:

fun main() {
fun factorial(n: Int): Int {
if (n <= 1) return 1
return n * factorial(n - 1)
}
println(factorial(10))
}

Local functions can call themselves recursively.

Top-level functions can reference each other regardless of declaration order:

fun isEven(n: Int): Boolean = when {
n == 0 -> true
else -> isOdd(n - 1)
}
fun isOdd(n: Int): Boolean = when {
n == 0 -> false
else -> isEven(n - 1)
}

println is a compiler intrinsic with support for multiple types:

println("hello") // String
println(42) // Int
println(true) // Boolean
println() // blank line
FeatureNotes
Default argumentsfun f(x: Int = 0)
Named argumentsf(x = 1, y = 2)
Varargsfun f(vararg items: Int)
Lambdas{ x -> x + 1 }, { it + 1 }
Higher-order functionsFunctions that accept or return lambdas
Inline functionsinline fun
Operator overloadingoperator fun plus(other: T)