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

后端 未结 5 1159
醉梦人生
醉梦人生 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:34

    IF you dump the class by using javap you can found kotlin using a IntRef not a int for lambda accessing the mutable variable out of its scope, since in java variables out of the lambda scope are effectively-final or final which means you can't modify the variable at all, for example:

    // Kotlin 
    var value = 1; // kotlin compiler will using IntRef for mutable variable
    val inc = { value++ }; 
    inc();
    println(value);// 2;
    
    //Java
    IntRef value = new IntRef();
    value.element = 1;
    
    Runnable inc=()-> value.element++;
    inc.run();
    println(value.element);// 2;
    

    the code above are equality. so don't modify the mutable variables out of the lambda scope in multi-threads. it will resulting to the wrong result.

    another good usage is you needn't modify the mutable variable out of the lambda scope and want to improve the performance optimization. you can use an additional immutable variable to achieve the performance for the lambda , for example:

    var mutable = 1;
    val immutable = mutable; // kotlin compiler will using int 
    
    val inc = { immutable + 1 };
    

提交回复
热议问题