1. Introduction
When you start writing Kotlin, it can sometimes feel like a strict teacher: “No, you can’t do that. And you can’t do that. And you can’t do that either. And anyway, why are you looking at me like that?” In reality, it’s not pedantry—it’s protection against silent errors that, in other languages, can quietly change what your program means. In Kotlin, almost any numeric type conversions are done explicitly—that is, you write what you want yourself.
Imagine: you calculate a discount in percent, store it as a Double, and then somewhere you “accidentally” turn it into an Int, and the fractional part disappears. If the language does this automatically, you can live with a bug like “the discount is sometimes weird” for weeks until you catch the right moment. Kotlin forces you to write .toInt(), and thereby kind of asks: “Are you sure you want to throw away the fraction? Really sure-sure?”
This rule doesn’t apply only to fractions. Kotlin doesn’t like “implicit widening” like Int → Double, even if it’s conceptually safe. So instead of “magic,” we have simple, readable methods: toDouble(), toFloat(), toInt(), and in the world of characters we also have the relationship Char ↔ number.
2. Basic number conversions
When you see a call like x.toInt(), it’s useful to think not “Kotlin did something,” but “I asked Kotlin to perform a specific operation.” This is an important habit: if you don’t formulate the action, later it will be hard to explain to yourself (and to a mentor) why the answer “drifted.”
Below is a simple table that helps keep the meaning of basic conversions in mind:
| Conversion | Example | What happens | Where data loss can occur |
|---|---|---|---|
|
|
the number becomes fractional; the value is preserved | usually no |
|
|
the number becomes fractional, but Float is less precise | sometimes yes (with large numbers) |
|
|
the fractional part is discarded (not rounded!) | yes, always if there is a fraction |
|
|
may become Infinity or be heavily distorted | yes |
|
|
precision is not “restored,” but the type becomes Double | data may have already been lost earlier |
We won’t dive into bits and memory layout right now (that’s a separate topic), but the practical takeaway is simple: converting “down” in type size (for example, Double → Int, Double → Float) is almost always potentially dangerous.
Look at this in code.
fun main() {
val x = 10
val d = x.toDouble()
println("x = $x") // x = 10
println("d = $d") // d = 10.0
}
Everything is fine here: Int → Double preserves the value; it just adds the “ability to have a fractional part.”
Now here’s an example where data is lost:
fun main() {
val price = 199.99
val asInt = price.toInt()
println("price = $price") // price = 199.99
println("asInt = $asInt") // asInt = 199
}
Final reminder: toInt() does not round; it cuts off the fractional part (essentially moves toward zero). If you want to round “like a human,” you do that separately (you already know round/floor/ceil from the previous lecture), and only then convert the type.
3. Mixing types and silent loss of meaning
When you write small practice programs, it feels like type conversions are rare. But once you have a “real” calculation (average, percent, probability, money), it suddenly turns out that half the bugs are not about if or loops, but about the wrong type in the wrong place.
A very typical scenario: we want an average. We have a sum (Int) and a count (Int). If we divide as Int / Int, the fractional part will disappear. So we must explicitly convert to Double in at least one part of the expression.
fun main() {
val sum = 7
val count = 2
val avg1 = sum / count
val avg2 = sum.toDouble() / count
println("avg1 = $avg1") // avg1 = 3
println("avg2 = $avg2") // avg2 = 3.5
}
Start building a programmer’s mindset: we are not “fixing Kotlin,” we are stating the computation rule. If we want a fraction, we make it a fraction.
Another common case is mixing Float and Double. Kotlin doesn’t like it when you accidentally mix two different floating types. Usually it’s easier to pick Double as the main type, and use Float only if there is a clear reason.
4. Char: one character and why it’s useful
Now we move on to a new type—the Char type. In Kotlin, Char is a single character, written in single quotes: 'A', '7', '?'. Char literals are in single quotes, and special characters are specified via escape sequences.
Why does this matter? Because beginners often confuse:
- '7' — the character seven (type Char)
- "7" — a string of length 1 (type String)
- 7 — a number (type Int)
And these are three different things. Sometimes they can be converted between each other, but Kotlin does not do it automatically so you don’t do something silly by accident (and you would—I know you; we’re all like that).
Also, Char often appears in strings: a string is a sequence of characters, and you can take individual characters by index.
Escape characters: '\n', '\t', and others
After getting familiar with strings, it’s useful to understand that some characters can be hard to write “as is.” That’s why escape sequences exist: '\n' is a new line, '\t' is a tab, etc. They also belong to Char.
fun main() {
val a = 'A'
val tab = '\t'
val nl = '\n'
println("[$a]") // [A]
println("x${tab}y") // x y
println("line1${nl}line2") // line1
// line2
}
Here, tab and nl are exactly characters, not magic printing commands.
5. Char and numbers: codes, toChar(), and digits
Now comes the part that makes you a little more of a “computer shaman.” The idea is simple: a character has a numeric code. On the JVM, Char is a 16-bit Unicode character. That means you can view a character as a number—and vice versa, you can turn a number into a character (if it falls into the valid range).
In Kotlin, a character has the code property, which gives the numeric code of the character (Int). And the reverse operation is toChar() on a number.
fun main() {
val ch: Char = 'A'
val code: Int = ch.code
val back: Char = code.toChar()
println("ch = $ch") // ch = A
println("code = $code") // code = 65
println("back = $back") // back = A
}
This looks like a trick, but it’s really just two reciprocal conversions.
The most popular practical example is digits. Keyboard input often comes in as text. Even if you’re not parsing a whole Int, sometimes you need to take one digit as a character, verify that it’s a digit, and turn it into a number.
Also, with codes you can do “shifts”: 'A' + 1 → 'B', '0' + 7 → '7'. In Kotlin, this kind of idea appears, for example, in problems where characters are compared and converted like numbers.
“Digit character” → number without magic
Converting '7' into the number 7 is a classic. Beginners often try something like:
- "7".toInt() — this works for a string, but not for Char
- ('7').toInt() — you can’t do this, because Char does not automatically turn into a “digit value”
- 7.toChar() — this is the opposite direction and will give not '7', but the character with code 7 (which is a control character)
The correct approach is this: if we have a character ch, and we are sure it is in the range '0'..'9', then the digit value equals the difference of codes: digit = ch.code - '0'.code
First, let’s check that it really is a digit.
fun main() {
val ch = '7'
val isDigit = ch >= '0' && ch <= '9'
val digit = if (isDigit) ch.code - '0'.code else -1
println("isDigit = $isDigit") // isDigit = true
println("digit = $digit") // digit = 7
}
Here, -1 is just an “error signal” within the example: if it’s not a digit, we return a value that definitely cannot be a digit. Later, when we have more serious approaches to errors, we’ll do it differently, but for now this is enough.
It’s important to notice that this style (character comparisons, ranges, and conversion via codes) is not invented for aesthetics— it really appears in real Kotlin code, especially in algorithmic problems.
6. Mini-scenario: generating a coupon from letters and digits
Imagine we’re making a console mini-app called LuckyCoupon. It prints a discount percentage to the user and a coupon code in the format A7Q2 (letter–digit–letter–digit). No loops—just four steps so we don’t get distracted from the point.
The key idea: to get a random letter, we take a random number 0..25, add it to the code of 'A', and convert back to Char.
import kotlin.random.Random
fun main() {
val letter1 = ('A'.code + Random.nextInt(0, 26)).toChar() // 'A'..'Z'
val digit1 = ('0'.code + Random.nextInt(0, 10)).toChar() // '0'..'9'
val letter2 = ('A'.code + Random.nextInt(0, 26)).toChar()
val digit2 = ('0'.code + Random.nextInt(0, 10)).toChar()
val code = "$letter1$digit1$letter2$digit2"
println("Your coupon: $code") // example: A7Q2
}
Notice two important things.
First: there is no “conversion magic” here. We explicitly work with codes via .code and toChar(). This makes the code a bit longer, but much clearer: from a number we made a character code; from a code we made a character.
Second: we carefully use the bounds nextInt(0, 26) and nextInt(0, 10). The upper bound is exclusive, which means we cover exactly 26 letters of the Latin alphabet—precisely and without surprises.
Discount and the place where the fraction often gets lost
Let the discount be computed as a Double (for example, you got a “floating” discount). For output, we want the percent as an integer. Here it’s important to choose: do we cut off the fraction or round? Now we’ll show exactly the fraction loss so you can see the difference.
fun main() {
val discount = kotlin.random.Random.nextDouble() * 30.0 // 0.0..30.0
val discountInt = discount.toInt() // cut off the fraction
println("discount = $discount") // discount = 12.345678...
println("discountInt = $discountInt%") // discountInt = 12%
}
If you want to round “by the rules,” you now know that you need to do that as a separate step.
7. Cheat-sheet diagram for conversions
Sometimes it’s useful to keep in mind not individual methods, but a small “route” for solving the problem. Here’s a simple flowchart that helps you not confuse “cutting off the fraction” with “rounding,” and also remember that characters live in the world of codes.
flowchart TD
A["You have a value"] --> B{Is it a number or a character?}
B -->|Number| C{Need a different numeric type?}
C -->|Yes| D["Explicitly: toDouble/toFloat/toInt"]
C -->|No| E["Keep as is"]
D --> F{Converting from Double to Int?}
F -->|Yes| G["Be aware: the fraction will be lost"]
F -->|No| H["Usually safer"]
B -->|Char character| I["Take ch.code (Int)"]
I --> J{Want a digit?}
J -->|Yes| K["Check '0'..'9' and subtract '0'.code"]
J -->|No| L["Convert number ↔ character via toChar()"]
8. Common mistakes
Mistake #1: confusing '7', "7", and 7.
These are three different types: Char, String, and Int. If you store a digit as a Char, it is not the number 7 and not the string "7". Trying to apply string methods to a Char or expecting a Char to “become a number” by itself is a common cause of confusion and weird conversions.
Mistake #2: thinking that toInt() rounds.
toInt() does not round; it discards the fractional part. This is especially annoying when you expect “a discount of 12.9% will become 13%,” but you get 12%. Kotlin is not to blame here: it did exactly what you asked. If you need rounding math—round first, then convert to Int.
Mistake #3: doing Double → Int “somewhere later,” without thinking about meaning.
Sometimes people write “for now let it be a Double, and at the end I’ll turn it into an Int.” This is dangerous: you might lose data at the moment when it’s already too late to understand where the error came from. It’s better to keep an agreement: where we store the precise computation (Double), and where we specifically need an integer result (Int), and do the conversion in a clear place.
Mistake #4: converting a digit from Char to Int without checking the range.
The expression ch.code - '0'.code is correct only if ch is actually in the range '0'..'9'. If it turns out to be 'A', you’ll get some number (for example, 17), and the program won’t crash—it will just start doing nonsense. So: check first, then convert.
Mistake #5: forgetting that Char is a Unicode character, not “a letter from the ASCII table.”
In learning examples, we calmly use 'A'..'Z' and '0'..'9', and it works predictably. But it’s important to remember that Char in Kotlin is Unicode, and “letters” are not only Latin. That’s exactly why it’s more correct to think in terms of “character code” and concrete ranges than in terms of “well, it’s a letter, so plus one will be the next one.”
GO TO FULL VERSION