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

Viewed 9335

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
4 Answers

val use to declare final variable. Characteristics of val variables

  1. Must be initialized
  2. value can not be changed or reassign

enter image description here

var is as a general variable

  1. We can initialize later by using lateinit modifier

    [lateinit also use for global variable we can not use it for local variable]

  2. value can be changed or reassign but not in global scope

enter image description here

val in kotlin is like final keyword in java

In kotlin we can declare variable in two types: val and var. val cannot be reassigned, it works as a final variable.

val x = 2
x=3 // cannot be reassigned

On the other side, var can be reassigned it is mutable

var x = 2
x=3 // can be reassigned
Related