Why the code in an object expression can access variables from the scope that contains it in kotlin?

后端 未结 5 1182
醉梦人生
醉梦人生 2021-01-01 10:49

In Kotlin,the code in an object expression can access variables from the scope that contains it, just like the following code:

fun countClicks(window: JCompo         


        
5条回答
  •  失恋的感觉
    2021-01-01 11:27

    In Kotlin, unlike Java, lambda expressions or anonymous function (as well as local functions and object expressions) can access and modify their closure - variables declared in outer scope. This behavior is as-designed.

    Higher order functions and lambdas - Closures

    Why Java does not allow this and Kotlin does - capturing closures introduces additional run-time overhead. Java uses simple and fast approach at cost of functionality. Kotlin on the other hand gives you more features - functionality, but it also generates more code behind the scenes to support it.

    At the end it is about writing less code to achieve something. If you want to translate above code to Java, it would be more complex.

提交回复
热议问题