Cookie Preferences

We use cookies to enhance your experience. Choose your preference for cookie usage.

Essential cookies are required for basic functionality. Additional cookies help us improve our service and provide analytics.

View third-party services
  • Google Analytics: Website traffic analysis and conversion tracking
  • RudderStack: Analysis of user interactions with the website
  • Microsoft Clarity: User behavior analysis & session recordings
  • Facebook Pixel: Marketing analysis of user activity
KotlinData types and variables

Type conversion

Converting between numeric types

In practice, you will usually use three numeric types: Int, Long, and Double. Sometimes, you may need to assign the value of one numeric type to a variable of another numeric type. To do that, you must perform a type conversion by invoking a special function such as toInt(), toLong(), toDouble(), and so on.

Suppose you have a variable called num of the Int type, and want to pass it to a function called sqrt, which finds the square root of a number. This function takes Double rather than Int, so you should convert the value using toDouble() to prevent a type mismatch error.

val num: Int = 100

val res: Double = Math.sqrt(num.toDouble())
println(res) // 10.0

println(num) // 100, it does not modified

Note: The variable types are specified to make the explanation more convenient for beginners.

Here is an important point: toDouble() does not modify the type of num — that is impossible. It produces a new value of Double type.

Such conversions are needed even when the target type is larger (e.g., Long, 64 bits) than the source type (e.g., Int, 32 bits). This greatly distinguishes Kotlin from other similar languages like Java and C#, in which a number of a smaller type can be assigned to a variable of a larger type without additional actions.

val num: Int = 100
val bigNum: Long = num.toLong() // 100

Despite the fact that Char is not a numeric type, it is possible to convert a number to a character and vice versa according to the character code (which can be found in the Unicode table). This code can be considered as an integer number.

val n1: Int = 125
val ch: Char = n1.toChar() // '}'
val n2: Int = ch.toInt()   // 125

If you have a value of a floating-point type (e.g., Double), you may convert it to a value of an integer type such as Int or Long.

val d: Double = 12.5
val n: Long = d.toLong() // 12

As you can see, the fractional part is simply ignored.

It is possible to convert a number from a larger type (e.g. Long or Double) to a smaller type (e.g., Int) using the functions mentioned above.

val d: Double = 10.2
val n: Long = 15

val res1: Int = d.toInt() // 10
val res2: Int = n.toInt() // 15

However, this conversion may truncate the value, because Long and Double can store a much larger number than Int.

val bigNum: Long = 100_000_000_000_000

val n: Int = bigNum.toInt() // 276447232; oops

Oops! The value has been truncated. This problem is known as type overflow. The same problem may occur when converting Int to Short or Byte. Convert from a larger type to a smaller type only when you are absolutely sure that it is necessary, and that truncation will not interfere with your program.

Converting to and from a String

Sometimes you need to get the string representation of a number or value of another type. Kotlin provides a useful function called toString() for converting something to a string.

val n = 8     // Int
val d = 10.09 // Double
val c = '@'   // Char
val b = true  // Boolean

val s1 = n.toString() // "8"
val s2 = d.toString() // "10.09"
val s3 = c.toString() // "@"
val s4 = b.toString() // "true"

A string can be converted to a number or even a boolean value (but not to a single character).

val n = "8".toInt() // Int
val d = "10.09".toDouble() // Double
val b = "true".toBoolean() // Boolean

If a string representation of a number has an invalid format, then an error called an exception will occur during the conversion. The program will stop if you do not take special actions, which we will discuss later.

However, when converting a string to a boolean value, no errors will occur. If the string has an unsuitable value (e.g. "tru"), the result of the conversion will be false.

val b1 = "false".toBoolean() // false
val b2 = "tru".toBoolean()   // false
val b3 = "true".toBoolean()  // true

Demonstration

To demonstrate the functions discussed above, here is a program that reads a string representation of a number, converts it to several other types, then prints the results of all the conversions.

import java.util.*

fun main(args: Array<String>) {
    val scanner = Scanner(System.`in`)
    val something = scanner.nextLine()

    val d = something.toDouble()
    val f = d.toFloat()
    val i = f.toInt()
    val b = i.toByte()

    println(d)
    println(f)
    println(i)
    println(b)
    println(something.toBoolean())
}

Suppose we have the following input:

1000.0123456789

The program prints:

1000.0123456789
1000.0123
1000
-24
false

Let's examine this output. The number represented by a string is successfully converted to Double because it has a suitable format. This number can be saved in Double without loss. Then the number is converted to Float with a loss, because this type can store fewer decimal numbers. The conversion to Int just cuts the fractional part. The number 1000 is larger than Byte can store (from -128 to 127), so here is a type overflow (-24). The result of converting the input string to Boolean is false, because the value is not "true".

We hope this lesson has helped you understand the principles of conversion between basic data types.
How did you like the theory?
Report a typo