Function definition: fun vs val
Answer #1 100 %Kotlin is all about Java interoperability and defining a function as a val
will produce a completely different result in terms of the interoperability. The following Kotlin class:
class A {
fun f(x: Int) = 42
val g = fun(x: Int) = 42
}
is effectively equivalent to:
public class A {
private final Function1 gref = new Function1() {
@Override
public Integer invoke(final Integer integer) {
return 42;
}
};
public int f(final int value) {
return 42;
}
public Function1 getG() {
return gref;
}
}
As you can see, the main differences are:
fun f
is just a usual method, whileval g
in fact is a higher-order function that returns another functionval g
involves creation of a new class which isn't good if you are targeting Androidval g
requires unnecessary boxing and unboxingval g
cannot be easily invoked from java:A().g(42)
in Kotlin vsnew A().getG().invoke(42)
in Java
UPDATE:
Regarding the A::f
syntax. The compiler will generate an extra Function2
class for every A::f
occurrence, so the following code results in two extra classes with 7 methods each:
val first = A::f
val second = A::f
Kotlin compiler isn't smart enough at the moment to optimize such kind of things. You can vote for the issue here https://youtrack.jetbrains.com/issue/KT-9831. In case you are interested, here is how each class looks in the bytecode: https://gist.github.com/nsk-mironov/fc13f2075bfa05d8a3c3
Tags: kotlin