Lambdas assigned to variables in Kotlin. Why?

  • A+
Category:Languages

I noticed that I get the same effect if I define this trivial function:

fun double ( i: Int ) = i*2 

and if I define a variable and assign a lambda (with an identical body) to it:

var double = { i : Int -> i*2 } 

I get the same result if I call double(a) with either declaration. This leaves me confused. When is it needed, recommended, advantageous to define a variable as a lambda rather than define a function to it?

 


When is it needed, recommended, advantageous to define a variable as a lambda rather than define a function to it?

Whenever you have the choice of either, you should use a fun declaration. Even with a fun you can still get a first-class callable object from it by using a function reference.

On the JVM, a fun is significantly more lightweight, both in terms of RAM and invocation overhead. It compiles into a Java method, whereas a val compiles into an instance field + getter + a synthetic class that implements a functional interface + a singleton instance of that class that you must fetch, dereference, and invoke a method on it.

You should consider a function-typed val or var only when something is forcing you to do it. One example is that you can dynamically replace a var and effectively change the definition of the function. You may also receive function objects from the outside, or you may need to comply with an API that needs them.

In any case, if you ever use a function-typed property of a class, you'll know why you're doing it.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: