Kotlin Variable

Kotlin Variables are containers for storing data values. The data of variables can be changed and reused depending on conditions.

To create a variable we can use var or val, and assign a value to it with an equal sign (=)

Variable Declarations

Kotlin uses two keywords to declare variables val and var.

Example :

 

Here the variable subject is a string type and the variable salary is an int type. so we don’t need to specify the type of variable explicitly. Kotlin compilers know this by initializer  Expression.

We can also explicitly specify the type of variable

Example :

You can also declare a variable without assigning the value, and give the value later. and this is only possible when you specify the type.

Example :

 

Difference Between val and var

 

Example :

var (mutable variables):-  we can change the value of variables declared using the var keyword.

Example :

Leave a Reply