Functors Â
What if I told you that you already use functors in Kotlin? Surprised? Let's have a look at the following code:
fun main(args: Array<String>) { listOf(1, 2, 3) .map { i -> i * 2 } .map(Int::toString) .forEach(::println) }
The List<T>
class has a function, map(transform: (T) -> R): List<R>
. Where does the name map
come from? It came from category theory. What we do when we transform from Int
to String
, is we map from the Int
category to the String
category. In the same sense, in our example, we transform from List<Int>
to List<Int>
 (not that exciting), and then from List<Int>
to List<String>
. We didn't change the external type, just the internal value.
And that is a functor. A functor is a type that defines a way to transform or to map its content. You can find different definitions of a functor, more or less academic; but in principle, all point to the same direction.
Let's define a generic interface...