Kotlin Variables
![Kotlin Variables](/content/images/size/w2000/2021/06/Green-and-White-Illustration-Science-Class-Education-Presentation--8---1-.png)
Kotlin has two different ways to declare variables: val
(immutable variable) and var
(mutable variable). The main between them is mutability.If you are planning to reassign value to variable use var
, otherwise use val
If you try to reassign the constant variable which is val
, in the Intellij IDE, you will see the following error.
![](https://mobiledevtutorials.com/content/images/2021/06/Screenshot-2021-06-08-at-22.48.16.png)
When you define a variable and you assign it a value, Kotlin implicitly infers the type of it. it means you can safely remove type in here.
![](https://mobiledevtutorials.com/content/images/2021/06/Screenshot-2021-06-08-at-22.54.53.png)
Lets make some example to understand better
// Don't work
var aVar;
// It works
var aVar1 : String = "hello world"
// It works
var number : Int? = null
// Don't compile
var aVar2: String?;
// works
val aConstant : String? = "constant Value"
// works
var aVariable2 = "hello Kotlin"