Kotlin First-Class Functions
Overview
Most recently created languages that support functional programming also support first-class functions. Java 8 also recently started supporting first-class functions.
What is a first-class function? It means that a programming language can handle functions as values. In other words, a first-class function is a function treated as an object.
First-class functions have the following characteristics.
- They can be assigned to variables.
- They can be passed as arguments to other functions or methods.
- They can be passed as return values from other functions or methods.
In Kotlin, functions can be assigned to variables, passed to functions as arguments, or received as return values, just like other values. A function that has become the same form as other values is conveniently called a function object.
Can Be Assigned to Variables
The following example assigns a function to a variable.
fun main() {
val hello: () -> String = { "Hello world!" }
println(hello())
}
Output:
Hello world!
In the example above, a function that returns the string "Hello world!" is assigned to the variable hello.
Can Be Passed as an Argument to Another Function or Method
The following example passes a function as an argument.
fun printlnFunc(func: () -> String) {
println("${func()}")
}
fun main() {
val hello: () -> String = { "Hello world!" }
printlnFunc(hello)
}
Output:
Hello world!
In the example above, the printlnFunc() function receives a function that returns a string as an argument. In main(), the hello function variable is passed to printlnFunc().
Can Be Passed as the Return Value of Another Function or Method
The following example returns a function.
fun getFunc(): () -> String {
return { "Hello world!" }
}
fun main() {
val returned: () -> String = getFunc()
println("${returned()}")
}
Output:
Hello world!
In the example above, the getFunc() function returns a function that returns a string. The main() function receives and calls that function, printing the string Hello world!.