A FunctionN interface is the compiler-generated representation of a Kotlin function value. The N identifies the number of parameters, while the interface exposes invoke to execute the function. section 10.1.3
A function type maps to Function1
The type (Int) -> Int corresponds to Function1<Int, Int>. A function accepting one integer and returning one integer can therefore be invoked directly or through invoke; both forms execute the same function value. section 10.1.3
interface Function1<P1, out R> {
operator fun invoke(p1: P1): R
}
The interface shape makes the generated representation explicit: the parameter type is accepted by invoke, and the return type is produced from it. section 10.1.3
The representation has several practical consequences:
- Function0<R> represents a function with no parameters; Function1<P1, R> represents one parameter, with corresponding interfaces for additional parameters. section 10.1.3
- Function values are instances of classes implementing the matching interface, with the lambda body held by invoke. section 10.1.3
- These interfaces can be used wherever interfaces are accepted, although implementing one directly is rarely practical. section 10.1.3
- Function interfaces are contravariant in parameter types and covariant in return types, matching the variance of Kotlin function types. section 11.3.4
- Non-inline higher-order operations can store lambdas as anonymous classes implementing a function interface. section 10.2.2
class Adder : (Int, Int) -> Int { #1
override operator fun invoke(
p1: Int,
p2: Int
): Int {
return p1 + p2
}
}
A class can implement a function type directly by overriding invoke, demonstrating that callable objects and function values share the same interface model. section 10.1.3
