In Scala, 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 and .toInt.
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check