Left Index

Kotlin Variables

Variable contains some data like other language, Kotlin also have variables. In Kotlin we can define variable using var keyword, for example: in below code snippet we define three type of variable i.e. String, Integer and float just using var keyword.

Example:
var empName = "John Carlo"
var empAge = 34
var salary = 80000f

There are two of variable in Kotlin:

  • Immutable using val keyword
  • Mutable using var keyword

Immutable Variables

Immutable Variables are read only that can not change later once define. We can create Immutable Variable using val keyword, for ex:


Mutable Variable

Mutable variable can defined using var keyword, and can change at any time within scope, for example:

Example:
package com.theitbulls.kotlinex

fun main(args: Array<String>) {
	var empName = "John Carlo"
	var empAge = 34
	var salary = 80000f

	println("name: ${empName}\nAge: ${empAge}\nSalry: ${salary}")
}
Output:
name: John Carlo
Age: 34
Salry: 80000.0

Scope of Variable: variable scope exists only within code block{...}