Let's Understand Kotlin Data Types


In this article, we'll learn basic data types used in Kotlin programming language: numbers, characters, booleans, arrays, and strings.
Note: Kotlin variables are declared using either var or val keyword.

1. Numbers
The representation of numbers in Kotlin is pretty similar to Java, however, Kotlin does not support implicit widening conversions. 

Below table shows basic built-in types with length:
TypeBit width
Double64
Float32
Long64
Int32
Short16
Byte8
Note:
Longs are tagged by a capital L: 123L
Doubles by default: 123.5, 123.5e10
Floats are tagged by f or F: 123.5f

Boolean
Boolean in Kotlin is very simple like other programming languages. There are only two values for Boolean – either true or false.

2.Character and Strings
In Kotlin, Characters are represented by the keyword Char. Character literals should be declared in a single quote like ‘K’. Special characters can be escaped using a backslash like \t .

Strings:
Strings are character arrays. Like java. It's declared by String. We have two kinds of string available in Kotlin - one is called raw String and another is called escaped String. String literals should be declared in a double quote like "Kotlin".

Note: Characters can not be treated directly as numbers.

Example:
fun main(args: Array<String>) {
   val obj : Char    // for strings : val obj : String
   Obj = 'K'        // for strings : obj = "Kotlin"
   println("$obj")
}

Output: k

3. Arrays
Arrays are a collection of similar type of data. Array is represented by the Array class, that has get and set functions. Kotlin supports arrays of different data types. Like ByteArray, ShortArray, IntArray and so on.

Example:
fun main(args: Array<String>) {
   val numbers: IntArray = intArrayOf(1, 2, 3)
   println("Hey!! I am array Example"+numbers[2])
}
Output : 3
Because index value starts with 0.

Comments