Variables in Kotlin, differences with Java: 'var' vs. 'val'?

Navjot.jassal :

I am trying to learn Kotlin. What is val, var and internal in Kotlin compared to Java?

In Java:

 RadioGroup radioGroup;
 RadioButton button;
 Button submit;

After converting it shows:

 internal var radioGroup: RadioGroup
 internal var button: RadioButton
 internal var submit: Button
zsmb13 :

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;

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 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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=430940&siteId=1