Kotlin scope functions are actually java anonymous classes?

Viewed 290

I'm currently working on some old Java written Android project, but writing new parts in Kotlin which I'm not really familiar with. I need some way to unwrap nullable object(analogue of if let unwrappedMyVar = myVar else {} in Swift), to do this I use myVar?.let {} scope function which unwraps myWar and executes block in case it is not null. But now I'm actually curious how those scope functions are implemented in Kotlin, are the actually compiled to Java anonymous classes ? If so, then it can lead to the same problems that Java anonymous classes have. And it is quite easy to create the leak
Thank you !
Kind Regards,
Andre

1 Answers

The scope functions like let, apply, run, or also, as well as many more functions in the Kotlin standard library, are inline functions, which means that the lambdas that you pass to them get inlined in their bodies, and the transformed bodies then get inlined at the call site.

With the scope functions, the resulting bytecode is mostly equivalent to what you would get with just declaring a variable and using it after an explicit if-null-check.

Related