Variables and Data Types in Kotlin

Variables in Kotlin:

Variables in Kotlin can be easily defined as mutable (var) or immutable (Val). The idea is very similar to using final in Java variables. But immutability is a very important concept in Kotlin (and many other modern languages).

An immutable object is an object whose state cannot be changed after instantiation. If you need a modified version, a new object needs to be created. This makes software much more robust and predictable. In Java, most objects are mutable, which means that any part of the code which has access to it can modify it, affecting the rest of the application.

Immutable objects are also thread-safe by definition. No special access control must be defined as they can’t change because all threads will always get the same object. So the way we think about coding changes a bit in Kotlin if we want to make use of immutability. The key concept: just use val as much as possible. There will be
situations (especially in Android, where we don’t have access to the constructor of many classes) where it won’t be possible, but it will most of the time.

Another thing mentioned before is that we usually don’t need to specify object types, they will be inferred from the value, which makes the code cleaner and faster to modify.

Example:

val s = "Example" // A String
val i = 23 // An Int
val actionBar = supportActionBar  // An ActionBar in an Activity context

However, a type needs to be specified if we want to use a more generic type:

val a: Any = 23
val c: Context = activity

Data Types in Kotlin:

There are four basic Data Types in Kotlin.

i. Integer: It stores whole numbers, positive or negative (such as 123 or -456), without decimals. The range of Integer data type is -231 to 231-1

ii. Float: It represents the numbers with a fractional part, containing one or more decimals. There are two types of Floating data types in Kotlin:

  • Float
  • Double
  • iii. Character: It is represented using the keyword Char. These data types are declared using single quotes ().

    iv. Boolean: It is represented using the type Boolean. It contains values either true or false.