Kotlin中的变量,与Java的差异:'var'与'val'? [英] Variables in Kotlin, differences with Java: 'var' vs. 'val'?
问题描述
我正在尝试学习 Kotlin 。与Kotlin相比,什么是 val
, var
和内部
Java?
I am trying to learn Kotlin. What is val
, var
and internal
in Kotlin compared to Java?
在Java中:
RadioGroup radioGroup;
RadioButton button;
Button submit;
转换后显示:
internal var radioGroup: RadioGroup
internal var button: RadioButton
internal var submit: Button
推荐答案
val
和 var
是您可以使用两个关键字来声明变量(和属性)。区别在于使用 val
为您提供了一个只读变量,这与使用 final
关键字相同Java的。
val
and var
are the two keywords you can use to declare variables (and properties). The difference is that using val
gives you a read-only variable, which is the same as using the final
keyword in Java.
var x = 10 // int x = 10;
val y = 25 // final int y = 25;
只要可以使用 val
在Kotlin中,如果你知道你将在某个地方改变它的价值,你应该只做 var
。
Using val
whenever you can is the convention in Kotlin, and you should only make something a var
if you know that you'll be changing its value somewhere.
See the official documentation about defining local variables and declaring properties.
internal
是Java中不存在的可见性修饰符。它标记了一个类的成员,它只能在它所在的模块中可见。这与默认的包
可见性在Java中提供的类似可见性(这就是为什么当转换成员 package
visibility时,转换器会使用它。但是,它并不完全相同。此外,请注意,这不是Kotlin中的默认可见性,默认情况下,Kotlin中的类及其成员 public
。
internal
is a visibility modifier that doesn't exist in Java. It marks a member of a class that will only be visible within the module it's in. This is a similar visibility to what the default package
visibility gives you in Java (which is why the converter would use it when converting members with package
visibility). However, it's not exactly the same. Also, note that it's not the default visibility in Kotlin, classes and their members in Kotlin are public
by default.
有关可见性修饰符的文档中有更多内容。
There is more in the documentation about visiblity modifiers.
这篇关于Kotlin中的变量,与Java的差异:'var'与'val'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!