Kotlin Variables and Data Types

In this article, You’ll learn how to declare variables in Kotlin, how Kotlin infers the type of variables, and what are the basic data types supported by Kotlin for creating variables.

You’ll also learn how to work with various data types and how to convert one type to another.

Variables

A variable refers to a memory location that stores some data. It has a name and an associated type. The type of a variable defines the range of values that the variable can hold, and the operations that can be done on those values.

You can declare a variable in Kotlin using var and val keywords.

A variable declared using val keyword is immutable (read-only). It cannot be reassigned after it is initialized -

val name = "Bill Gates"
name = "Satoshi Nakamoto"	// Error: Val cannot be reassigned 

For defining a mutable variable, i.e. a variable whose value can be changed, use the var keyword -

var country = "USA"
country = "India"    // Works

Type inference

Did you notice one thing about the variable declarations in the previous section? We didn’t specify the type of variables.

Although Kotlin is a statically typed language, It doesn’t require you to explicitly specify the type of every variable you declare. It can infer the type of a variable from the initializer expression -

val greeting = "Hello, World"  // type inferred as `String`
val year = 2018                // type inferred as `Int`

If you want to explicitly specify the type of a variable, you can do that like this -

// Explicitly defining the type of variables
val greeting: String = "Hello, World" 
val year: Int = 2018

Note that the type declaration becomes mandatory if you’re not initializing the variable at the time of declaration -

var language   // Error: The variable must either have a Type annotation or be initialized
language =  "French"

The above variable declaration fails because Kotlin has no way to infer the type of the variable without an initializer expression. In this case, you must explicitly specify the type of the variable -

var language: String   // Works
language = "French"

Data Types

Data Types are used to categorize a set of related values and define the operations that can be done on them.

Just like other languages, Kotlin has predefined types like Int, Double Boolean, Char etc.

In Kotlin, everything (even the basic types like Int and Boolean) is an object. More specifically, everything behaves like an Object.

Kotlin may represent some of the basic types like numbers, characters and booleans as primitive values at runtime to improve performance, but for the end users, all of them are objects.

This is contrary to languages like Java that has separate primitive types like int, doubleetc, and their corresponding wrapper types like Integer, Double etc.

Let’s now look at all the basic data types used in Kotlin one by one -

Numbers

Numeric types in Kotlin are similar to Java. They can be categorized into integer and floating point types.

Integers

  • Byte - 8 bit
  • Short- 16 bit
  • Int - 32 bit
  • Long - 64 bit

Floating Point Numbers

  • Float - 32 bit single-precision floating point value.
  • Double - 64 bit double-precision floating point value.

Following are few examples of numeric types -

// Kotlin Numeric Types Examples
val myByte: Byte = 10
val myShort: Short = 125

val myInt = 1000
val myLong = 1000L	// The suffix 'L' is used to specify a long value

val myFloat = 126.78f   // The suffix 'f' or 'F' represents a Float 
val myDouble = 325.49

You can also use underscore in numeric values to make them more readable -

val hundredThousand = 100_000
val oneMillion = 1_000_000

You can declare hexadecimal and binary values like this -

val myHexa = 0x0A0F  // Hexadecimal values are prefixed with '0x' or '0X'
val myBinary = 0b1010  // Binary values are prefixed with '0b' or '0B'

Note that Kotlin doesn’t have any representation for octal values.

Booleans

The type Boolean is used to represent logical values. It can have two possible values true and false.

val myBoolean = true
val anotherBoolean = false

Characters

Characters are represented using the type Char. Unlike Java, Char types cannot be treated as numbers. They are declared using single quotes like this -

val letterChar = 'A'
val digitChar = '9'

Just like other languages, special characters in Kotlin are escaped using a backslash. Some examples of escaped characters are - \n (newline), \t (tab), \r (carriage return), \b (backspace) etc.

Strings

Strings are represented using the String class. They are immutable, that means you cannot modify a String by changing some of its elements.

You can declare a String like this -

var myStr = "Hello, Kotlin"

You can access the character at a particular index in a String using str[index]. The index starts from zero -

var name = "John"
var firstCharInName = name[0]  // 'J'
var lastCharInName = name[name.length - 1]  // 'n'

The length property is used to get the length of a String.

Escaped String and Raw String

Strings declared in double quotes can have escaped characters like ‘\n’ (new line), ‘\t’ (tab) etc -

var myEscapedString = "Hello Reader,\nWelcome to my Blog"

In Kotlin, you also have an option to declare raw strings. These Strings have no escaping and can span multiple lines -

var myMultilineRawString = """
    The Quick Brown Fox
    Jumped Over a Lazy Dog.
"""

Arrays

Arrays in Kotlin are represented using the Array class. You can create an array in Kotlin either using the library function arrayOf() or using the Array() constructor.

Creating Arrays using the arrayOf library function

You can pass a bunch of values to the arrayOf function to create an array like this -

var numbers = arrayOf(1, 2, 3, 4, 5)
var animals = arrayOf("Cat", "Dog", "Lion", "Tiger")

Note that you can also pass values of mixed types to the arrayOf() function, and it will still work (but don’t do that) -

var mixedArray = arrayOf(1, true, 3, "Hello", 'A')	// Works and creates an array of Objects

You can also enforce a particular type while creating the array like this -

var numArray = arrayOf<Int>(1, 2, 3, 4, "Hello")  // Compiler Error

Accessing the elements of an array by their index

You can access the element at a particular index in an array using array[index]. The index starts from zero -

val myDoubleArray = arrayOf(4.0, 6.9, 1.7, 12.3, 5.4)
val firstElement = myDoubleArray[0]
val lastElement = myDoubleArray[myDoubleArray.size - 1]

Every array has a size property that you can use to get the size of the array.

You can also modify the array element at an index like this -

val a = arrayOf(4, 5, 7)  // [4, 5, 7]
a[1] = 10		          // [4, 10, 7]	

Primitive Arrays

As we learned earlier, everything in Kotlin is an object. But to improve performance it represents some of the basic types like numbers, characters and booleans as primitive types at runtime.

The arrayOf() function creates arrays of boxed/wrapper types. That is, arrayOf(1, 2, 3) corresponds to Java’s Integer[] array.

But, Kotlin provides a way to create arrays of primitive types as well. It contains specialized classes for representing array of primitive types. Those classes are - IntArray, DoubleArray, CharArray etc. You can create an array of primitive types using the corresponding library functions - intArrayOf(), doubleArrayOf(), charArrayOf() etc. -

val myCharArray = charArrayOf('K', 'O', 'T')  // CharArray (corresponds to Java 'char[]')
val myIntArray = intArrayOf(1, 3, 5, 7)		// IntArray (corresponds to Java 'int[]')

Creating Arrays using the Array() constructor

The Array() constructor takes two arguments -

  1. the size of the array, and
  2. a function that takes the array index as an argument and returns the element to be inserted at that index.
var mySquareArray = Array(5, {i -> i * i})	// [0, 1, 4, 9, 16]

The second argument to the Array() constructor is a lambda expression. Lambda expressions are anonymous functions that are declared and passed around as expressions. We’ll learn more about lambda expressions in a future tutorial.

The above lambda expression takes the index of an array element and returns the value that should be inserted at that index, which is the square of the index in this case.

Type Conversions

Unlike Java, Kotlin doesn’t support implicit conversion from smaller types to larger types. For example, Int cannot be assigned to Long or Double.

var myInt = 100
var myLong: Long = myInt // Compiler Error

However, Every number type contains helper functions that can be used to explicitly convert one type to another.

Following helper functions are supported for type conversion between numeric types -

  • toByte()
  • toShort()
  • toInt()
  • toLong()
  • toFLoat()
  • toDouble()
  • toChar()

Examples of explicit type conversions

Here is how you can convert an Int to Long -

val myInt = 100
val myLong = myInt.toLong()   // Explicitly converting 'Int' to 'Long'

You can also convert larger types to smaller types -

val doubleValue = 176.80
val intValue = doubleValue.toInt()  // 176

Every type in Kotlin, not just numeric type, supports a helper function called toString() to convert it to String.

val myInt = 1000
myInt.toString()  // "1000"

You can also convert a String to a numeric type like so -

val str = "1000"
val intValue = str.toInt()

If the String-to-Number conversion is not possible then a NumberFormatException is thrown -

val str = "1000ABC"
str.toInt()   // Throws java.lang.NumberFormatException

Conclusion

That’s all folks! In this article, You learned how to declare mutable and immutable variables. How type inference works in Kotlin. What are the basic data types supported in Kotlin. How to work with data types like Int, Long Double, Char, Boolean, String and Array, and how to convert one type to another.