Skip to main content

Variables in Kotlin

  • Variables are named memory location where we can store values temporarily.
  • As the name suggests, variables vary over time.
  • For example: a variable can have value 3 now, and then 5 later.
  • The var keyword is used for declaring variables in Kotlin.

var x = 3
var y = 4
Kotlin also offers read only variables or values.
  • Values do not change over time and remain constant.
  • Declare values in Kotlin using val keyword.
  • Kotlin throws an error if trying to reassign another value to a read only variable.
val PI = 3.14 // PI is a read-only variable now
// reassigning is not allowed
PI = 3.1415
So far, we didn't need to specify the type of variable.
  • Kotlin infers the type of variable from the value assigned to variable.
  • But we can also explicitly specify the type of variable (or values).
var z: Int = 3
var msg: String = "Hello World"
val PI: Double = 3.1415
Can we have variables with null values?
  • Sometimes when programming, we don't know the value of variable immediately.
  • In such cases, we end up declaring a variable without any value and then assign a value to it later.
  • Kotlin lets us define a variable with null value as too.
  • The question mark at the end of variable declaration specifies that the variable can have null values.

// declare a variable without any value
var area:Int?
// some code or processing block: eg: get side_a and side_b from user
// now assign the value
area = side_a * side_b

Comments