Kotlin Variables

Kotlin Variables

Variables are containers for storing data values. In Kotlin, you declare a variable using either the var or val keyword.


var vs val

Example

fun main() {
  var name = "John"
  name = "Robert" // This is allowed because 'name' is a var

val birthYear = 1990 // birthYear = 1995 // ERROR: Val cannot be reassigned!

println(name) println(birthYear) }


Type Inference

Notice in the example above that we did not specify the type of data (like String or Integer). Kotlin is smart enough to understand that "John" is a text string and 1990 is a number. This feature is called Type Inference.

However, you can explicitly specify the type if you want to (or need to declare a variable without immediately assigning it a value).

Explicit Typing

fun main() {
  val name: String = "John"
  val age: Int = 30
}