A variable is a location in memory that holds data. This tutorial will help you learn about variables in Kotlin, how they are created, and the basic data types that Kotlin supports for creating these variables.

Declaring a variable in Kotlin

To declare a variable in Kotlin, either var or val keyword can be used. Here is an example:

var country = "Australia"
val count = 75

Here, country is a variable of type String, and count is a variable of type Int. You don’t have to specify the type of variables; Kotlin implicitly does that for you. The compiler knows this by initializer expression ("Australia" is a String, and 75 is an integer value in the above program). This is also known as type inference in programming.

However, you can explicitly specify the type if you want to:

var country: String = "Australia"
val count: Int = 75

We have initialized variable during declaration in above examples. However, it’s not necessary. You can declare variable and specify its type in one statement, and initialize the variable in another statement later in the program.

var country: String      // variable declaration of type String
... .. ...
country = "Australia"       // variable initialization

val count: Int          // variable declaration of type Int 
... .. ...
count = 75             // variable initialization

Here are few examples that results into error.

var country           // Error 
country = "Australia"

Here, the type of country variable is not explicitly specified, nor the variable is initialized during declaration.

var country: String
country = 22         // Error

Here, we are trying to assign 22 (integer value) to variable of different type (String).

What is the Difference Between var and val?

  • val (Immutable reference) – The variable declared using val keyword cannot be changed once the value is assigned. It is similar to final variable in Java.
  • var (Mutable reference) – The variable declared using var keyword can be changed later in the program. It corresponds to regular Java variable.

Here are few examples:

var country = "Australia"
country = "England"

Here country variable is reassigned to England. The variable is declared using var so this code works perfectly.

val country = "Australia"
country = "England"      // Error

You cannot reassign country variable to England in the above example because the variable is declared using val.

Basic Types in Kotlin

Kotlin is a statically typed language like Java. That is, the type of a variable is known during the compile time. For example,

val eggs: Int
val marks = 5.8

The compiler knows that eggs is of type Int, and marks is of type Doublebefore the compile time.

The built-in types in Kotlin are:

  • Numbers
  • Characters
  • Booleans
  • Arrays

Number

Numbers in Kotlin are similar to Java. There are 6 built-in types representing numbers.

  • Byte
  • Short
  • Int
  • Long
  • Float
  • Double

Byte

  • The Byte data type can have values from -128 to 127 (8-bit signed two’s complement integer).
  • It is used instead of Int or other integer data types to save memory if it’s certain that the value of a variable will be within [-128, 127]
  • Example:
    fun main(args : Array<String>) {
        val range: Byte = 112
        println("$range")
    
        // The code below gives error. Why?
        // val range1: Byte = 200
    }

When you run the program, the output will be:

112

Short

  • The Short data type can have values from -32768 to 32767 (16-bit signed two’s complement integer).
  • It is used instead of other integer data types to save memory if it’s certain that the value of the variable will be within [-32768, 32767].
  • Example:
fun main(args : Array<String>) {

    val temperature: Short = -11245
    println("$temperature")
}

When you run the program, the output will be:

-11245

Int

  • The Int data type can have values from -231 to 231-1 (32-bit signed two’s complement integer).
  • Example:
fun main(args : Array<String>) {

    val score: Int =  100000
    println("$score")
}

When you run the program, the output will be:

100000

If you assign an integer between -231 to 231-1 to a variable without explicitly specifying its type, the variable will be of Int type. For example,

fun main(args : Array<String>) {

   // score is of type Int
    val score = 10
    println("$score")
}

Long

  • The Long data type can have values from -263 to 263-1 (64-bit signed two’s complement integer).
  • Example:
fun main(args : Array<String>) {

    val highestScore: Long = 9999
    println("$highestScore")
}

When you run the program, the output will be:

9999

If you assign an integer value greater than 231-1 or less than -231 to a variable (without explicitly specifying its type), the variable will be of Long type. For example,

val distance = 10000000000  // distance variable of type Long

Similarly, you can use capital letter L to specify that the variable is of type Long. For example,

val distance = 100L    // distance value of type Long

Double

  • The Double type is a double-precision 64-bit floating point.
  • Example:
fun main(args : Array<String>) {

    // distance is of type Double
    val distance = 999.5
    println("$distance")
}

When you run the program, the output will be:

999.5

Float

  • The Float data type is a single-precision 32-bit floating point.
  • Example:
fun main(args : Array<String>) {

    // distance is of type Float
    val distance = 19.5F
    println("$distance")
}

When you run the program, the output will be:

19.5

Notice that, we have used 19.5F instead of 19.5 in the above program. It is because 19.5is a Double literal, and you cannot assign Double value to a variable of type Float.

To tell compiler to treat 19.5 as Float, you need to use F at the end.

If you are not sure what number value a variable will be assigned in the program, you can specify it as Number type. This allows you to assign both integer and floating-point value to the variable (one at a time). For example:

fun main(args : Array<String>) {

    var test: Number = 12.2
    println("$test")

    test = 12
    // Int smart cast from Number
    println("$test")

    test = 120L
    // Long smart cast from Number
    println("$test")
}

When you run the program, the output will be:

12.2
12
120

Char

To represent a character in Kotlin, Char types are used.

Unlike Java, Char types cannot be treated as numbers.

fun main(args : Array<String>) {

    val letter: Char
    letter = 'k'
    println("$letter")
}

When you run the program, the output will be:

k

In Java, you can do something like:

char letter = 65;

However, the following code gives error in Kotlin.

var letter: Char = 65  // Error

Boolean

  • The Boolean data type has two possible values, either true or false.
  • Example:
fun main(args : Array<String>) {

    val flag = true
    println("$flag")
}

Booleans are used in decision making statements (will be discussed in later chapter).

Arrays

An array is a container that holds data (values) of one single type. For example, you can create an array that can hold 100 values of Int type.

In Kotlin, arrays are represented by the Array class. The class has get and set functions, size property, and a few other useful member functions. To create an array, we can use a library function arrayOf() and pass the item values to it, so that arrayOf(1, 2, 3) creates an array [1, 2, 3].

Another option is to use a factory function that takes the array size and the function that can return the initial value of each array element given its index:

// Creates an Array<String> with values ["0", "1", "4", "9", "16"]
val asc = Array(5, { i -> (i * i).toString() })

Strings

In Kotlin, strings are represented by the String class. The string literals such as "this is a string" is implemented as an instance of this class. Since literals in Kotlin are implemented as instances of String class, you can use several methods and properties of this class.

  • length property – returns the length of character sequence of an string.
  • compareTo function – compares this String (object) with the specified object. Returns 0 if the object is equal to the specfied object.
  • get function – returns character at the specified index.
    You can use index access operator instead of get function as index access operator internally calls get function.
  • plus function – returns a new string which is obtained by the concatenation of this string and the string passed to this function.
    You can use + operator instead of plus function as + operator calls plus function under the hood.
  • subSequence Function – returns a new character sequence starting at the specified start and end index.

This tutorial was reposted from Programiz with additions