Kotlin, Zero to Kotlin Hero

Zero to Kotlin Hero : Variables and Data Types

In my previous article, I introduced the Zero to Kotlin Hero series.

In this article, we would cover data types and how to declare variables in Kotlin.

 

A variable is a storage location (identified by a memory address) paired with an associated symbolic name (an identifier), which contains some known or unknown quantity of information referred to as a value – Wikipedia

To declare a Kotlin variable, either a var or val keyword is used. To further describe the image above, there are two types of variables in Kotlin: mutable and immutable variables.

 

Mutable variables

A mutable variable is a variable whose state can be modified after it is created. This just basically means read and write. In Kotlin, mutable variables are declared with the var keyword. Referring to the image above, let’s see the boxes as storage locations for different values. The var box is open. This means that a value can go into it and can be removed from it. When a variable is declared with the var keyword, that variable’s value can be changed later in the code. An example is shown below:

var myName = "Adora"

//some more code here ....

myName = "Nenne"   //myName is now Nenne

 

Immutable variables

An immutable variable is a variable whose state cannot be modified after it is created. This basically means read-only. In Kotlin, immutable variables are declared with the val keyword. Referring to the image above, we can see that the val box is closed. This means that the value inside the box cannot be removed. When a variable is declared with the val keyword, that variable’s value can’t be changed later in the code. An example is shown below:

val myName = "Adora" 

//some more code here .... 

myName = "Nenne"   //ERROR!

Kotlin’s val keyword does the same thing that Java’s private static final myAge = "Nenne"; would do. But hey, it’s shorter with Kotlin. It is important to note that immutable variables are preferred whenever possible. This is particularly good in multithreading as it helps promote thread safety.

 

Since we have seen the two forms a Kotlin variable can take, we can go into the data types in Kotlin.

 

Kotlin Data Types

The data types in Kotlin can be categorized into five:

  • Numbers
  • Characters
  • Boolean
  • Strings
  • Arrays

Numbers

Kotlin provides the following built-in types representing numbers:

Type Size
Double 64
Float 32
Long 64
Int 32
Short 16
Byte 8

We can declare number variables in Kotlin like this:

fun main() {
    val myDouble: Double = 2020.0
    val myFloat: Float = 222.0f
    val myLong: Long = 903999938L
    val myInt: Int = 300
    val myShort: Short = 15
    val myByte: Byte = 2
}

Note: In Kotlin, simpler numeric types cannot be assigned to complex types. e.g. Putting a byte inside an int is not allowed.

val x: Byte = 2
val y: Int = x     //This does not compile

Characters

Characters in Kotlin are declared using the char keyword and are represented in single quotes. In Kotlin, Characters cannot be declared like number variables. We can declare characters in Kotlin like this:

fun main() { 
    val firstLetter: Char = 'A' 
}

 

Boolean

Booleans have only two values: true or false. We can declare booleans in Kotlin like this:

fun main() { 
   val isFemale: Boolean = true
   val isMale: Boolean = false 
}

 

Strings

A string is an array of characters. Strings are immutable. Kotlin has two types of strings. Escaped strings that may have escaped characters in them, and raw strings that can contain newlines and arbitrary text.

This is an example of an escaped string:

val myString = "Hi, I am Adora!\n"

A raw string uses triple quotes ("""), contains no escaping and can contain newlines and any other characters. A raw string can be defined like this

val text = """
   for (a in "nenne")
      print a
"""

 

Arrays

Arrays in Kotlin are represented by the Array class. To create an array, we can use a library function arrayOf() and pass the item values to it, so that arrayOf(1, 2, 3, 4, 5) creates an array [1, 2, 3, 4, 5].

val arr = arrayOf(1, 2, 3, 4, 5);  //Array with values ["1", "2", "3", "4", "5"]

Kotlin also has specialized classes to represent arrays of primitive types without boxing overhead:  ByteArrayShortArrayIntArray and so on. These classes have no inheritance relation to the Array class, but they have the same set of methods and properties.

val numberslist: IntArray = intArrayOf(100, 200, 300, 400, 500)
val secondnumberslist: byteArray = byteArrayOf(10, 20, 30, 40, 50)

 

Another way of declaring variables

In Kotlin, Variables can also be declared without adding the data type to the declaration. For example, if I declare a character:

val c = 'A'

Kotlin immediately knows that c is a character because Kotlin uses type inference. This makes your code shorter.

 

Kotlin is statically typed

One difference between a language like Python and Kotlin is that Python is dynamically typed and Kotlin is statically typed. In Kotlin, everything is an object, and every object has a type. In Python, the same name can be assigned to all kinds of different objects:

# Python
thevalue = 22         # int
thevalue = "nenne"    # str

#this would work in python

However, in a statically typed programming language like Kotlin, a variable can only be assigned to objects of one fixed type, the type of the variable:

var myString : String = "Something about a lazy fox"
myString = "Another string"         // ok
myString = 14           // error! Int value cannot be in string variable
myString = false        // error! Boolean value cannot be in string variable

The advantage of a statically typed language is that the compiler can catch type errors during the compilation before the program is even run.

 

Conclusion

We have seen the difference between mutable and immutable variables in Kotlin. If you want to see more examples on Kotlin variables, please go to my GitHub. Get ready to know about Kotlin classes in the next article!

 

Spread the love

2 thoughts on “Zero to Kotlin Hero : Variables and Data Types

    1. Collectively, yes. Each category can be broken down into subcategories. e.g. Numbers are signed or unsigned. The signed numbers are Int, Double, Byte etc. and the unsigned numbers are UByte, UInt, ULong etc.
      So its not 5 data types. It’s five categories. There are a lot of data types. I hope I could explain it better, but you can also check the official documentation too. https://kotlinlang.org/docs/reference/basic-types.html.

Leave a Reply

Your email address will not be published. Required fields are marked *