Thuta Learning
Kotlin
BasicProgrammingBeginner

Data Types

KotlinLesson 630 min

What you'll walk away with

  • Choose between Int, Long and Double, and read literals such as `1_000`, `5L` and `2.5f`
  • Explain why `val big: Long = intValue` is rejected and fix it with `toLong()`
  • Predict integer division and the overflow result of `Int.MAX_VALUE + 1`
  • Use `Char` (`'a' + 1`, `.code`), `Boolean` and ranges (`in 1..10`)
  • Build text with string templates and `buildString`

Explain it simply

Data types, simply

A data type is a label that says what kind of value something is and what you can do with it. It is like measuring tools in a shop: you measure length with a ruler and weight with a scale. Kotlin likewise has a type for whole numbers, decimal numbers, a single character, true or false, and text.

Kotlin is strict about types. It never quietly turns one kind of number into another; if you want a conversion, you say so. That may feel fussy at first, but it protects you from values that go wrong without you noticing.

Problem → Why → Solution

The problem: numbers that give wrong answers without crashing

Look at a program that works with file sizes. `kilobytes` is 3,000,000, and multiplying it by 1024 should give 3,072,000,000. Instead the program prints the negative number `-1222967296`, with no error and no warning. The second problem is smaller but more common: dividing 7 + 8 by 2 gives 7, not 7.5.

sizes.kt
fun main() {
    val kilobytes = 3_000_000
    val bytes = kilobytes * 1024
    println("Bytes: $bytes")             // Bytes: -1222967296

    val total = 7 + 8
    println("Average: ${total / 2}")     // Average: 7
}

Why this happens

Kotlin treats a whole-number literal as an `Int`, and an `Int` has only 32 bits, so it can hold −2,147,483,648 to 2,147,483,647. Go beyond that and the value wraps around to the other end without any error. Dividing an `Int` by an `Int` is whole-number division, which throws the fraction away. The fix is to choose the wider `Long` or the decimal `Double`.

Core concept: types, conversions and their limits

The numeric types are split by size: `Byte`, `Short`, `Int` and `Long` for whole numbers, and `Float` and `Double` for decimals. When you have no reason to choose, use `Int` and `Double`, because Kotlin treats the literal `42` as an `Int` and `3.14` as a `Double`. A suffix such as `5L` makes a `Long`, and a whole-number literal too big for an `Int` is taken as a `Long` automatically. A `Float` is written with `f`, as in `2.5f`. Underscores, as in `1_000_000`, are allowed to make numbers readable.

TypeRange or precisionUse it for
Byte8-bit, −128 to 127Raw data and file bytes
Short16-bit, −32,768 to 32,767Rarely needed
Int32-bit, about ±2.1 billionThe default for counts and indexes
Long64-bit, about ±9.2 × 10^18File sizes, timestamps, IDs, big totals
Float32-bit, about 6 to 7 digitsGraphics, or when storage is tight
Double64-bit, about 15 to 16 digitsThe default for decimals and measurements

The most important rule is that there is no implicit widening. You cannot put an `Int` value into a `Long` variable directly: `val total: Long = count` (where `count` is an `Int`) fails with `error: initializer type mismatch: expected 'Long', actual 'Int'.` You convert by hand with `toLong()`, `toInt()` or `toDouble()`. Mixing numeric types in arithmetic is allowed, so `1 + 2L` is a `Long`, but comparing with `count == 5L` fails with `error: operator '==' cannot be applied to 'Int' and 'Long'.`

Converting to a smaller type can lose information. `3.99.toInt()` is 3 (the fraction is cut off, not rounded), and `300.toByte()` is 44 (the excess wraps). Go past the range of an integer type and `Int.MAX_VALUE + 1` becomes `-2147483648`, with no exception. To catch overflow, use Java's `Math.addExact(a, b)`, which throws `ArithmeticException: integer overflow`. Also `7 / 2` is 3, `7 / 2.0` is 3.5, `7 % 2` is 1 and `-7 / 2` is -3 (division truncates toward zero).

A `Char` is a single Unicode character written in single quotes, such as `'K'`. `'c' + 1` is `'d'`, `'c' - 'a'` is the Int 2 and `'c'.code` is 99. A `Boolean` is only ever `true` or `false` and combines with `&&` (both true), `||` (either true) and `!` (reverse). A `String` is a sequence of characters that cannot be changed (it is immutable). `word[0]` returns a `Char`, and `word[0] = 'k'` fails with `error: no 'set' operator method providing array access.`

Mental model: fixed types, manual conversions
  1. Every value has one fixed type
  2. Types never convert silently
  3. Convert explicitly: toLong(), toInt()
  4. Overflow wraps, it never complains

Kotlin catches a type mismatch while you type, but it does not catch a number going out of range, not even at run time.

General pattern: types and conversions

kotlin
val whole: Int = 42
val big: Long = 5_000_000_000L
val decimal: Double = 3.14
val letter: Char = 'K'
val flag: Boolean = true
val text: String = "Kotlin"
val widened: Long = whole.toLong()

A type is written after the name as `: Type`, and when you leave it out Kotlin infers it from the value. A `Long` literal ends in `L`, a `Char` uses single quotes and a `String` double quotes. The last line converts an `Int` to a `Long` by hand.

The facts of one book

This program stores the facts of a book in several types and shows three conversions: `Int` to `Long`, `Double` to `Int`, and adding to a `Char`. The last line lets you see overflow with your own eyes. Predict the output before you run it.

Book.kt
fun main() {
    val title: String = "Kotlin Basics"
    val pages: Int = 320
    val price: Double = 19.99
    val grade: Char = 'A'
    val inStock: Boolean = true

    val copies: Long = pages.toLong() * 1_000_000
    val dollars: Int = price.toInt()
    val nextGrade: Char = grade + 1

    println("$title: $pages pages, price $price, grade $grade, in stock: $inStock")
    println("Copies: $copies, whole dollars: $dollars, next grade: $nextGrade")
    println("Int.MAX_VALUE + 1 = ${Int.MAX_VALUE + 1}")
}

Code breakdown

  1. Explicit typesval price: Double = 19.99

    The `: Double` is optional, because Kotlin would infer `Double` from `19.99`; every type is written out here on purpose. You cannot give a Double a whole-number literal as in `val price: Double = 20`; you must write `20.0`.

  2. Int widened to Longval copies: Long = pages.toLong() * 1_000_000

    `pages.toLong()` first turns 320 into a `Long`, and then it is multiplied. A `Long` times an `Int` is a `Long`, which matches `copies: Long`. The underscore in `1_000_000` only makes it easier to read.

  3. Double narrowed to Intval dollars: Int = price.toInt()

    `19.99.toInt()` cuts the fraction and gives 19, not 20. Kotlin makes you call `toInt()` yourself so the loss is visible. To round instead, use `kotlin.math.roundToInt()`.

  4. Char arithmeticval nextGrade: Char = grade + 1

    A `Char` plus an `Int` is a `Char`: the letter after `'A'` is `'B'`. Two Chars cannot be added together (`'a' + 'b'` fails with an `argument type mismatch` error), but subtracting one from the other gives an `Int`.

  5. Several values in one lineprintln("$title: $pages pages, price $price, grade $grade, in stock: $inStock")

    One template can mix many types. Kotlin shows the `Int` as `320`, the `Double` as `19.99`, the `Char` as `A` and the `Boolean` as `true`.

  6. Silent overflowprintln("Int.MAX_VALUE + 1 = ${Int.MAX_VALUE + 1}")

    `Int.MAX_VALUE` is the largest `Int`, 2147483647. Adding 1 wraps around to the lowest value and prints `-2147483648`. The compiler gives no warning and no exception is thrown.

You should see
Kotlin Basics: 320 pages, price 19.99, grade A, in stock: true
Copies: 320000000, whole dollars: 19, next grade: B
Int.MAX_VALUE + 1 = -2147483648

Arithmetic and overflow step by step

The program below shows the lesson's number rules one line at a time. Cover the results in the comments, guess them yourself, then run it and compare. Notice that `big.toLong() + 1` widens first and then adds, so it does not overflow.

Numbers.kt
fun main() {
    val big = 2_147_483_647
    println(big + 1)               // -2147483648 (wraps around)
    println(big.toLong() + 1)      // 2147483648 (widen first, then add)
    println(7 / 2)                 // 3 (whole-number division)
    println(7 / 2.0)               // 3.5 (one Double makes it Double)
    println(7 % 2)                 // 1 (remainder)
    println(3.99.toInt())          // 3 (cuts the fraction, no rounding)
    println(0.1 + 0.2)             // 0.30000000000000004 (binary fractions)
    println(1 + 2L)                // 3 (Int + Long is Long)
}

That `0.1 + 0.2` is not `0.3` is not a Kotlin problem. Computers store decimals in binary, and numbers such as `0.1` cannot be stored exactly. So avoid comparing two `Double` values with `==`, and do not use `Double` for money.

Char, Boolean and ranges

A `Char` has a numeric value, its Unicode code, which you can read with `.code`. Subtracting two characters gives their distance as an `Int`. A range is written `1..10` (both ends included) or `1 until 10` (end excluded), and together with `in` it produces a Boolean. Using ranges in loops comes in later lessons.

Chars.kt
fun main() {
    val letter = 'c'
    println(letter + 1)               // d
    println(letter - 'a')             // 2
    println(letter.code)              // 99
    println(letter in 'a'..'z')       // true

    val age = 17
    val canVote = age >= 18
    val isTeen = age in 13..19
    println(canVote || isTeen)        // true
    println(!canVote && isTeen)       // true
}

Strings, buildString and parsing input

A String cannot change, so gluing a text together piece by piece creates new Strings over and over. To build longer text, use `buildString { ... }`: inside the braces you `append(...)` the pieces and the finished String is returned. When converting text typed by a user into a number, `"42".toInt()` can fail badly (`"abc".toInt()` throws an exception), so use `toIntOrNull()` and take `null` when it does not parse.

Strings.kt
fun main() {
    val word = "Kotlin"
    println(word.length)              // 6
    println(word[0])                  // K
    println(word.uppercase())         // KOTLIN

    val table = buildString {
        for (i in 1..3) {
            append("3 x ").append(i).append(" = ").append(3 * i).append('\n')
        }
    }
    print(table)

    println("42".toInt() + 1)         // 43
    println("abc".toIntOrNull())      // null
    println("3.5".toDoubleOrNull())   // 3.5
}

In real projects

How real projects choose types

In practice, choosing a type starts with two questions: how large can the data get, and how exact must it be? Counters and indexes use `Int`. Timestamps (`System.currentTimeMillis()` returns a `Long`), database IDs, file sizes and big totals use `Long`, because an `Int` silently breaks once it passes 2.1 billion. Measured values such as temperature or height use `Double`.

Money is normally not stored in a `Double`, because decimal rounding creates problems. Storing the smallest unit (a cent, a pya) in a `Long`, or using `BigDecimal`, is standard. Text coming from outside (a form, a file, an API) is checked with `toIntOrNull()` rather than `toInt()`, so one unexpected input does not bring the whole program down. That habit is also the foundation of the null safety lessons that come later.

Common mistakes

Common mistakes

1. Putting an Int straight into a Long or Double

With `val count: Int = 5`, writing `val total: Long = count` fails with `error: initializer type mismatch: expected 'Long', actual 'Int'.` and `val d: Double = count` fails the same way. Convert it yourself with `count.toLong()` or `count.toDouble()`. A comparison such as `count == 5L` is rejected too; just write `5`.

2. Writing a Char with double quotes

`val grade: Char = "A"` fails with `error: initializer type mismatch: expected 'Char', actual 'String'.` because `"A"` is a String. Use single quotes for a Char: `'A'`.

3. Expecting decimals from Int division, and overlooking overflow

`(7 + 8) / 2` is 7, not 7.5; give one side a Double such as `2.0` when you want decimals. When multiplying big numbers, putting the product of two `Int`s into a `Long` afterwards is too late, because it has already wrapped; call `toLong()` on one of the operands first.

4. Declaring a too-large literal as an Int

`val big: Int = 3000000000` fails with `error: initializer type mismatch: expected 'Int', actual 'Long'.` because the number does not fit in an `Int`. Leave the type off, as in `val big = 3_000_000_000`, and Kotlin takes it as a `Long`, or write `val big: Long = 3_000_000_000`.

Best practices

Best practices

  • Start with `Int` for whole numbers and `Double` for decimals; move to `Long` when values can get big.
  • Convert an operand before the arithmetic, as in `a.toLong() * b`, not `(a * b).toLong()`.
  • Write long numbers with underscores such as `1_000_000`, and use an uppercase `L` on `Long` literals.
  • Do not store money in a `Double`; store the smallest unit in a `Long`.
  • Convert user input with `toIntOrNull()` instead of `toInt()`.

Mini challenge

Mini challenge: a download size report

A download is given in megabytes. Work out the number of bytes correctly, and show next to it what goes wrong when the same maths is done with Int.

  • Declare `val megabytes = 3_000` (an Int)
  • Compute `wrongBytes` as `megabytes * 1024 * 1024` with Int only, and `bytes` by calling `toLong()` first
  • Compute `gigabytes` as a `Double` by dividing `bytes` by 1024³
  • Use a Boolean `fitsInInt` to test whether `bytes` fits within `Int.MAX_VALUE`, and print all four results, one per line
DownloadSize.kt
fun main() {
    val megabytes = 3_000
    // TODO: wrongBytes: plain Int arithmetic (megabytes * 1024 * 1024)
    // TODO: bytes: the same maths, but widen to Long first
    // TODO: gigabytes: bytes divided by 1024 cubed, as a Double
    // TODO: fitsInInt: a Boolean, does bytes fit within Int.MAX_VALUE?
    // TODO: print the four results, one per line
}

Expected: Prints: Int arithmetic: -1149239296 Long arithmetic: 3145728000 Gigabytes: 2.9296875 Fits in an Int: false

Show hint

In `megabytes.toLong() * 1024 * 1024` the first operand is a `Long`, so the rest of the maths continues as `Long`. For a Double write `bytes / (1024.0 * 1024 * 1024)`; the `1024.0` is a Double, so it is no longer whole-number division. A `Long` can be compared with an `Int` using `bytes <= Int.MAX_VALUE`.

Show solution
DownloadSize.kt
fun main() {
    val megabytes = 3_000

    val wrongBytes = megabytes * 1024 * 1024
    val bytes = megabytes.toLong() * 1024 * 1024
    val gigabytes = bytes / (1024.0 * 1024 * 1024)
    val fitsInInt = bytes <= Int.MAX_VALUE

    println("Int arithmetic: $wrongBytes")
    println("Long arithmetic: $bytes")
    println("Gigabytes: $gigabytes")
    println("Fits in an Int: $fitsInInt")
}

Quick quiz 1 / 3

What does `println(Int.MAX_VALUE + 1)` print?

Quick quiz 2 / 3

Given `val count: Int = 5`, which line compiles?

Quick quiz 3 / 3

What do `println(7 / 2)` and `println(7 / 2.0)` print, in that order?

What to remember

  • `Int` and `Double` are the defaults; `Long` comes from `5L` or `toLong()`, a Char uses single quotes and a String double quotes.
  • Kotlin has no implicit widening: call `toLong()`, `toInt()` and `toDouble()` yourself.
  • Integer overflow wraps without an error, `Int / Int` drops the fraction, and `toInt()` does not round.
  • `buildString` and string templates are good for building text, and `toIntOrNull()` parses input safely.

Kotlin language guide — Kotlin

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Data Types | Thuta Learning