Kotlin - val and var

Introduction

Kotlin has two keywords for declaring variables, val and var.

The var defines a variable. This is equivalent to declaring a variable in Java:

Demo

fun main(args: Array<String>) {
    var name = "java2s.com" 
    println(name)//from w w w  .j a v  a2 s .c o  m
}

The var defined variable can be initialized later:

Demo

fun main(args: Array<String>) {
    var name: String 
    name = "kotlin" 
    println(name)//from   ww w . j a  v a  2s  .  com
}

Variables defined with var can be reassigned:

Demo

fun main(args: Array<String>) {
    var name = "tutorial" 
    name = "more tutorial" 
    println(name)/*from  w w  w  . j  a  va  2  s .  com*/
}

Constant

The keyword val declares a read-only variable.

A val must be initialized when it is created, since it cannot be changed later:

Demo

fun main(args: Array<String>) {
    val name = "java2s.com" 
    println(name)//w  w w. j  a v  a  2 s.co m
}

A read only variable does not mean the instance itself is immutable.