This article will take about 2.8 minutes to read.

Source: www.jianshu.com/p/acc8d9a67d0c

During development, we may become accustomed to some of the features of a programming language for reasons of habit, especially if we use only one language for daily development.
However, when you develop in more than one language, even though they are high-level languages, there are many features that differ from one another.

The phenomenon of description

Prior to Java 8, anonymous inner classes reported errors and prompted when using external members
“Cannot refer to a non-final variable arg inside an inner class defined ina different method”:
But after Java 8, similar scenarios are no longer prompted:
Can such variables be changed at will? Of course not, you will still get an error when you try to modify these variables:
As you can see, when attempting to modify a variable of the base data type, the compiler’s warning becomes
“Varible ‘num’ is email exchange from within inner class, need to be final or effectively final”Unfortunately, it still cannot be modified. Kotlin, by contrast, has no such limit:

Cause analysis,

It’s hard to see why on the surface, but look what the compiler does! run

javac

The command generates several.class files:

The TestInnerClass$1.class is the compiled file of the anonymous inner class.
It turns out that anonymity is treated like a normal class, except that when the compiler generates its constructor, it passes in a reference to the external class as well as a copy of the variables of the base datatype and a reference to the variables of the datatype. Therefore, the variables of the primitive data type cannot be modified, otherwise they will be inconsistent with the external variables, and the passing of the variables will become meaningless.


Scene contrast

But why is it possible for Kotlin to modify the value of a primitive data type directly in an anonymous inner class? See what Kotlin compiled and decompiled back:

As you can see, when variables of primitive data types need to be passed, the Kotlin compiler wraps the data so that it changes from value to reference, so that internal changes do not of course affect external ones.


Verify what the Kotlin compiler does when a variable is not passed:
Ha ha, not to beat a dead horse, thumbs up!




, END,

The growth path of programmers

Though the road is long, the journey is sure to come

This article was originally posted on the wechat public account of the same name “The Growth of programmers”, reply to “1024” you know, give a thumbs up.

Reply [520] to receive the best learning method for programmers

Reply to [256] for Java programmer growth plans