Sunday 23 October 2016

Learn more on Scala Types : Converting Between Numeric Types : Day 3 Learnings

Converting Between Numeric Types (Casting)

You want to convert from one numeric type to another, such as from an Int to a Double . 

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        toShort     toString       toLong

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

Note: 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




Share this article with your friends.

No comments :

Post a Comment

Related Posts Plugin for WordPress, Blogger...