Sunday, 23 October 2016

Learn more on Scala Types : Numeric Data Types : Day 3 Learnings

Displays Scala’s numeric data types:

NameDescriptionSizeMinMax
ByteSigned integer1 byte-127128
ShortSigned integer2 bytes-3276832767
IntSigned integer4 bytes-2^312^31 - 1
LongSigned integer8 bytes-2^632^63 - 1
FloatSigned floating point4 bytesn/an/a
DoubleSigned floating point8 bytesn/an/a



Examples on Numeric Data Types:


Let’s try this out by creating values of different types and automatically converting them to higher-ranked types:

scala> val b: Byte = 30
b: Byte = 30

scala> val s: Short = b
s: Short = 10

scala> val d: Double = s
d: Double = 10.0

The b and s values here were assigned to new values that had a higher rank, and so were automatically converted (or upconverted” as some say) to the higher ranks.


Scala does not allow automatic conversion from higher ranked types to lower ranked types. This makes sense, because you could otherwise lose data if you convert to a type with less storage.

Here is an example of trying to automatically convert a higher ranked type to a lower ranked type and the ensuing error:

scala> val l: Long = 20
l: Long = 20

scala> val i: Int = l
<console>:8: error: type mismatch;
found : Long
required: Int
    val i: Int = l

You can choose to manually convert between types using the toType methods available on all numeric types. Although this makes it possible to lose data by converting to a lesser ranked type, it is useful when you know that the data is compatible with the lower ranked type

For example, here is a Long value that can be safely converted to type Int using the toInt method, because its data is within the storage bounds of an Int :

scala> val l: Long = 20
l: Long = 20

scala> val i: Int = l.toInt
i: Int = 20

If you ever need to know the exact values of the data ranges, you can find them in the Scala REPL:

scala> Short.MinValue
res0: Short = −32768

scala> Short.MaxValue
res1: Short = 32767

scala> Int.MinValue
res2: Int = −2147483648

scala> Float.MinValue
res3: Float = −3.4028235E38



Share this article with your friends.
Related Posts Plugin for WordPress, Blogger...