Kotlin Variables: In this tutorial, you will learn about kotlin variables, how to create them, and the fundamental data types that Kotlin supports for creating variables.

As you probably are aware, a variable is a location in memory (storage area) to hold data.

To show the storage area, every variable ought to be given a unique name (identifier).

Variable refers to a memory location. It is used to store data. The data of variable can be changed and reused relying upon condition or on data passed to the program.


How to declare a variable in Kotlin?

To declare a variable in Kotlin, either var or val catchphrase is used. Here is an examplel:

var language = "English"
val score = 95

The distinction in using var and val is examined later in the tutorial. Until further notice, let’s focus on the variable declaration.

Here, language is a variable of type String, and the score is a variable of type Int. You don’t need to indicate the type of variables; Kotlin verifiably does that for you. The compiler knows this by initializer expression (“English” is a String, and 95 is an integer value in the above program). This is called type inference in programming.

Be that as it may, you can explicitly specify the sort in the event that you need to:

var language: String = "English"
val score: Int = 95

We have introduced variables during declaration in the above examples. Be that as it may, it’s excessive. You can declare the variable and indicate its sort in one statement, and introduce the variable in another statement later in the program.

var language: String      // variable declaration of type String
... .. ...
language = "English"       // variable initialization

val score: Int          // variable declaration of type Int 
... .. ...
score = 95             // variable initialization 

Here are not many examples that outcomes into error.

var language           // Error 
language = "English"

Here, the type of language variable isn’t expressly determined, nor the variable is introduced during declaration.

var language: String
language = 14         // Error

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


Difference Between var and val

  • val (Immutable reference) – The variable declared using val catchphrase can’t be changed once the worth is assigned. It is like the final variable in Java.
  • var (Mutable reference) – The variable declared using var watchword can be changed later in the program. It relates to the regular Java variable.

Here are few examples:

var language = "English"
language = "German"     

Here, language variable is reassigned to German. Since, the variable is declared using var, this code work perfectly.

val language = "English"
language = "German"      // Error

You can’t reassign the language variable to German in the above example in light of the fact that the variable is declared using val.


Presently, you understand what Kotlin variables are, it’s time to learn various values a Kotlin variable can take.


Kotlin Basic Types

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

val language: Int
val marks = 12.3

Here, the compiler realizes that language is of type Int, and marks is of type Double before the compile time.

The built-in sorts in Kotlin can be arranged as:

  • Numbers
  • Characters
  • Booleans
  • Arrays

Number Type


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

  • Byte
  • Short
  • Int
  • Long
  • Float
  • Double
  1. Byte

  • The Byte data type can have values from – 128 to 127 (8-bit signed two’s complement integer).
  • It is used rather than Int or other integer data types to save memory if it’s sure that the value of a variable will be inside [-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

2. Short


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

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

When you run the program, the output will be:

-11245

3. 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

On the off chance that you assign an integer between – 231 to 231-1 to a variable without explicitly determining its sort, the variable will be of Int type. For instance,

fun main(args : Array<String>) {

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

On the off chance that you are using IntelliJ IDEA, you can put the cursor inside the variable and press Ctrl + Shift + P to see its sort.

4. 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

On the off chance that you assign an integer value greater than 231-1 or less than – 231 to a variable (without explicitly indicating its sort), the variable will be of the Long type. For instance,

val distance = 10000000000  // distance variable of type Long

Essentially, you can use capital letter L to determine that the variable is of type Long. For instance,

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

5. 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


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.5 is 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.


In the event that you don’t know what number value a variable will be assigned in the program, you can determine it as Number sort. This allows you to assign both integer and floating-point values to the variable (one at a time). For instance:

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. Visit this page to learn more about Java char Type.

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

fun main(args : Array<String>) {

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

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


Kotlin Arrays

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

In Kotlin, arrays are addressed by the Array class. The class has get and set functions, size property, and a couple of other useful number functions.


Kotlin Strings

In Kotlin, strings are addressed by the String class. The string literals, for example, “this is a string” is executed as an occasion of this class.


Recommended Readings

  • Type conversion in Kotlin
  • Smart casts in Kotlin
  • Kotlin nullable types

Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.