Start learning free

LESSON 15 OF 677 · VARIABLES

Type Conversion in Kotlin

Lesson

In Kotlin, every value has a type: Int, Double, String, and so on. Sometimes you need to convert a value from one type to another.

Common type conversion methods:

x.toString()       // converts Int or Double → String
s.toInt()          // converts String → Int
s.toDouble()       // converts String → Double
x.toInt()          // converts Double → Int (drops decimal)

Here are some examples:

val score = 42
val scoreStr = score.toString()    // "42"

val weight = 70.8
val weightInt = weight.toInt()     // 70  (decimal dropped)

val count = "100"
val countInt = count.toInt()       // 100

Note that converting a Double to Int with toInt() simply drops the decimal - it does not round.


Assignment
Follow the Coding Tutorial and convert each variable to a different type!


Hint
Use toString(), toInt(), and toDouble().

STEP 1 OF 3
    Ctrl + Enter to check