Start learning free

LESSON 15 OF 348 · VARIABLES

Type Conversion in Scala in Scala

Lesson

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.

STEP 1 OF 3
    Ctrl + Enter to check

    Type Conversion in Scala

    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free