Today we are going to learn about the keywords we are going in order to declare a variable in kotlin, those keyword are val and var.
There is not vast difference between them but it can create amajor changes in your program. Now let us see the difference among them.
- var:- It is also called general variable as it can be be used multiple times and it’s values can be set.
- val:-Whereas if we consider val. It is a type of final , we can not change its value once set.
We declare both in the same manner like below:-
val id=6
val id:Int=6
var id=6
var id:Int=6
So that was more or the same declaration and defining of variable in kotlin. But let me show you the code below, where on trying you can feel the difference on running it.
The above diagram shows the difference between val and var, and now let us see the program which will erase the doubts about the two keywords.
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
class MainActivity : AppCompatActivity() {
var id=5;
override fun onCreate(savedInstanceState: Bundle?) {
id=9
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var textVar= findViewById<TextView>(R.id.textView)
textVar.text= id.toString()
}
}
This program will give you no error as var is a general variable. Thus this program gives an output as 9, as it is an mutable variable, which adjusts to a value changes.
package adapter.manasvi.com.simpleproject
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
class MainActivity : AppCompatActivity() {
val id=5;
override fun onCreate(savedInstanceState: Bundle?) {
id=9 //This line of code will give an error.
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var textVar= findViewById<TextView>(R.id.textView)
textVar.text= id.toString()
}
}
This program will give you error as val is a immutable variable. Thus this program gives an error.
Feel free to try above example and comment below.