Is Kotlin a functional programming language?
It can be. Kotlin supports first-class functions and higher-order functions, and has a large standard library filled with useful functions that can be chained together to write highly functional code. Let's look at a few examples of functional code in Kotlin.
In the following snippet, you can see how Kotlin allows you to store a function as a variable:
fun main(args: Array<String>) {
// we can store a function as a variable
val stringFilter:(String) -> Boolean = { string ->
string.length > 3
}
}
This variable can then be used to invoke the function, or it can be passed to another function as an argument.
Here's an example of a higher-order function taken from the Kotlin standard library:
/**
* Returns a list containing only elements matching the given [predicate].
*/
public inline fun <T> Iterable<T>.filter(predicate: (T) -> Boolean): List<T> {
return filterTo(ArrayList<T>(), predicate)
}
The filter function takes a function as an argument that is used to filter items from the Iterable receiver. The passed argument will be called for each item in Iterable, and is used to determine whether or not to include the current item in the List<T> output.
In the following code, we can see how the previous two examples can be used together:
fun main(args: Array<String>) {
// we can store a function as a variable
val stringFilter:(String) -> Boolean = { string ->
string.length > 3
}
val languages = listOf("c++", "php", "java", "kotlin")
val filteredLanguages = languages.filter(stringFilter)
}
We use a standard library function to easily create a list of strings. We then call filter on that list, and pass in the function variable that we previously declared.
Finally, we can see how we could achieve the same output by chaining these functions together, as shown in the following code example:
val filteredLanguages = listOf("c++", "php", "java", "kotlin")
.filter { string ->
string.length > 3
}
In this case, we skip storing a function variable or the original list of strings, and compose a single chain of functional operators that defines our desired output. This functional composition has no side-effects, and produces the same output each time; so it adheres to the properties of functional programming that we discussed previously.