Kotlin Variables

A variable refers to a memory location that stores some data.
You can declare variables in kotlin using val and var keywords.

val:
Variable declared using val keyword is immutable(read only). It can not be reassigned after it is initialized.

val name = "Kotlin"
name = "Language" //Error: val can not be reassigned


It is similar to final variable in Java.

var:
Variable declared using var keyword is mutable. It can be reassigned after it is initialized.

val name = "Kotlin"
name = "Language" //No error. It works

It is similar to regular variable in Java.


Type inference:
In Kotlin, it is not mandatory to explicitly specify the type of variable that you declare. Kotlin compiler will automatically infer the type of the variable from the initializer section.

val name = "Kotlin" // type infered as "String"
val value = 100 //type infered as "Int"

You can also explicitly define the type of the variable.
val name: String = "Kotlin"
val value: Int = 100

Type of the variable declaration mandatory if you dont initialize the variable.

val name // Error: variable must either have a Type annotation or be initialized
name = "Kotlin"

You can also declare something like this.
val name: String //works
name = "Kotlin"

No comments:

Post a Comment