Unlike Java, which does not allow you to define functions outside of classes, Kotlin allows you to declare functions outside of classes, called free functions.
fun f(x : Int) : Int {
return x*x + 2*x - 1
}
let result = f(13)
Kotlin also offers a short-cut form, called a function with expression body, that is useful for simple functions:
fun f(x:Int) : Int = x*x + 2*x - 1
You can also declare methods inside classes, just as you would in Java. A Kotlin method declaration looks just like a regular function declaration and appears inside a class.
Kotlin allows you to declare default values for parameters that will be used when those parameters are missing in a function call.
fun incr(x : Int, deltax : Int = 1) : Int {
return x + deltax
}
var result = incr(42) // result is 43
result = incr(result,2) // result is 45
Lambda expressions have recently become widely used in modern programming. Kotlin offers strong support for lambda expressions, and makes them easy to use.
In Kotlin functions are first-class language elements, which means that they can be returned as results from other functions and passed as parameters to functions.
One example of a use case for passing functions as parameters is making it easier to customize functions. One typical example of function customization is a filtering function that takes two parameters, a list of data elements and a function that decides whether or not a given element should be kept in the result list. Below you will see examples of how to implement such a function in both Kotlin.
fun filter(list:List<Int>,keep:(Int)->Boolean) : List<Int> {
var result = mutableListOf<Int>()
for(x in list) {
if (keep(x)) {
result.add(x)
}
}
return result.toList()
}
fun keepPositive(x:Int) : Boolean = x >= 0
val originalList = listOf(2,-1,3,4,-6)
val filteredList = filter(originalList,keepPositive)
Lambda expressions offer a short-cut method for defining and using functions in one simple step. Here is an example with different filtering functions where we use lambda expressions to eliminate the need to define a filtering function when calling filter():
val evens = filter(originalList,{x->x%2==0})
Kotlin also offers a special shortcut syntax called a trailing lambda for situations where the last parameter passed to a function is a lambda expression:
val evens = filter(originalList) { x->x%2==0 }
Finally, another shortcut form that Kotlin offers is an even shorter expression for a lambda where we don't have to declare the parameters for the lambda. Kotlin uses the keyword it to stand for the sole parameter to a lambda expression in cases where the lambda has just one parameter.
val evens = filter(originalList) { it%2==0 }