Often, when using higher-order functions, we invoke them using function literals, especially if the function is short:
listOf(1, 2, 3).filter { it > 1 }
As you can see, there is no reason to define the passed function anywhere else. When using literals like this, we are unable to specify the return value. This is usually not a problem as the Kotlin compiler will infer the return type for us.
However, sometimes we may wish to be explicit about the return type. In those cases, we can use something called an anonymous function. This is a function that looks similar to a normal function definition, except the name is omitted:
fun(a: String, b: String): String = a + b
This can be used in the following manner:
val ints = listOf(1, 2, 3) val evens = ints.filter(fun(k: Int) = k % 2 == 0)
If the parameter type can also be inferred, then that...