Functions in the JVM
Prior to version 8 of the Java Virtual Machine (JVM), first class functions were not supported. Since Kotlin targets Java 6 for compatibility with Android devices, how are functions handled by the compiler?
It turns out that all functions in Kotlin are compiled into instances of classes called Function0
, Function1
, Function2
, and so on. The number in the class name represents the number of inputs. If you look at the type inside an IDE, you will be able to see which class the function is being compiled into. For example, a function with the signature (Int)->Boolean
would show the type as Function1<Int, Boolean>
. Each of the function classes also has an invoke member function that is used to apply the body of the function.
Here is the definition of Function0
from the Kotlin source code, which accepts no input parameters:
/** A function that takes 0 arguments. */ public interface Function0<out R> : Function<R> { /** Invokes the...