Finally understand why you want to add the final keyword!

Read this article takes about 2.8 minutes.

Source: www.jianshu.com/p/acc8d9a67d0c

During the development process, because of habit, we may take for granted some of the features of a programming language, especially one language as the daily development.
But when you use more than one language development when you will find, though they are high-level language, but they are not too many features between the same.

Symptom

Before Java 8, anonymous inner classes in the use of external members, will get an error and prompts  "Can not refer to a non- final variable arg inside an inner class defined in a different method":
But after Java 8, similar to the scene but no further suggests:
Is such variables can easily change it? Of course not, when you try to modify these variables, it still will prompt an error:
Can see that when you try to modify the basic data types of variables, compiler warnings became  "Varible 'num' is accessed from within inner class, need to be final or effectively final", unfortunately, still can not be modified. In contrast, Kotlin is no such limitation:

Cause Analysis

What reason can not see from the surface, of course, take a look at the compiler what has been done it! run
javac
.Class file into several epigenetic command:
Difficult to conclude that this TestInnerClass $ 1.class file is compiled after the anonymous inner class to see if it is what decompile:
原来,匿名也会被当作普通的类处理,只不过编译器生成它构造方法的时候,除了将外部类的引用传递了过来,还将基本数据类型的变量复制了一份过来,并把引用数据类型的变量引用也传递了过来。因此,基本数据类型的变量当然不能修改了,不然就会跟外部的变量产生不一致,这样的话变量的传递也就变得毫无意义了。

情景对比

但是为什么对于 Kotlin 来说可以在匿名内部类中直接修改基本数据类型的值呢?查看 Kotlin 编译后反编译回来的内容:

可以发现,当需要传递基本数据类型的变量时,Kotlin 编译器会将这些数据进行包装,从而由值传递变为引用传递,这样内部的修改当然就不会影响到外部了。
验证一下,当变量不进行传递时,Kotlin 编译器是怎么处理的:
哈哈,并没有多此一举,点个赞!

 

 

·END·

程序员的成长之路

路虽远,行则必至

本文原发于 同名微信公众号「程序员的成长之路」,回复「1024」你懂得,给个赞呗。

回复 [ 520 ] 领取程序员最佳学习方式

回复 [ 256 ] 查看 Java 程序员成长规划

 

Guess you like

Origin www.cnblogs.com/gdjk/p/11356875.html