2.2. Converting Between Numeric Types (Casting)
Problem
You want to convert from one numeric type to another, such as from
an Int
to a Double
.
Solution
Instead of using the “cast” approach in Java, use the to*
methods that are available on all numeric
types. These methods can be demonstrated in the REPL (note that you need
to hit Tab at the end of the first example):
scala>val b = a.to[Tab]
toByte toChar toDouble toFloat toInt toLong toShort toString scala>19.45.toInt
res0: Int = 19 scala>19.toFloat
res1: Float = 19.0 scala>19.toDouble
res2: Double = 19.0 scala>19.toLong
res3: Long = 19 scala>val b = a.toFloat
b: Float = 1945.0
Discussion
In Java, you convert from one numeric type to another by casting the types, like this:
int
a
=
(
int
)
100.00
;
But in Scala, you use the to*
methods, as shown in this recipe.
If you want to avoid potential conversion errors when casting from
one numeric type to another, you can use the related isValid
methods to test whether the type can
be converted before attempting the conversion. For instance, a Double
object (via RichDouble
) has methods like isValidInt
and isValidShort
:
scala>val a = 1000L
a: Long = 1000 scala>a.isValidByte
res0: Boolean = false scala>a.isValidShort
res1: Boolean = true
See Also
The RichDouble class |
Get Scala Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.