Displays Scala’s numeric data types:
Name | Description | Size | Min | Max |
Byte | Signed integer | 1 byte | -127 | 128 |
Short | Signed integer | 2 bytes | -32768 | 32767 |
Int | Signed integer | 4 bytes | -2^31 | 2^31 - 1 |
Long | Signed integer | 8 bytes | -2^63 | 2^63 - 1 |
Float | Signed floating point | 4 bytes | n/a | n/a |
Double | Signed floating point | 8 bytes | n/a | n/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.
No comments :
Post a Comment