Skip to main content

Kotlin - Variables and Type Inference


Unlike Java, Kotlin uses special keywords to declare variables.
  • var - for the values that change, mutable.
  • val - for the values that do not change, immutable.

String name = "Java";
int age = 20;

val name = "Kotlin"
val age = 4

It is best practice to use val because immutability guarantees safety.

We can use variable type when we declare it. If we initialize it, we can remove the type. But if we do not initialize, we should declare the variable type.
val name = "Jon Snow"

val role: String
role = "King in the north"


If the value is a truly constant we can const keyword when declaring. Though this needs to use companion object.
const val THE_END = "All men must die"

Type inference

Kotlin is a strongly typed language. Compiler can deduce the type by the context eliminating boilerplate code. Compiler is smart enough to identify the variable type.
val helpUs = "Save Wilpattu"
val pi = 3.14


It will print String and Double.