Now that you’ve seen strings and integers, a next good thing to know is that Scala comes with the following built-in numeric data types:
Byte
Short
Int
Long
Float
Double
And when you’re working with extremely large numbers you can also use:
BigInt
BigDecimal
Scala’s numeric data types
As a practical matter, until numbers get very large, most programmers generally use integers (Int
) and double values (Double
). Because of that, these are the defaults in Scala, as you can see in the REPL:
scala> val x = 42
val x: Int = 42
scala> val y = 42.0
val y: Double = 42.0
When I create x
, Scala is smart enough to implicitly know that x
is an Int
, and when I create y
, Scala also implicitly infers that it is a Double
.
On the rare occasions that you might need to use the other numeric data types, declare them when you create your variables, like this:
val a: Byte = 1
val b: Long = 1
val c: Short = 1
val d: Float = 1.0
// you can also declare Int and Double this way,
// though it isn’t necessary:
val e: Int = 1
val f: Double = 1.0
Scala 3 also lets you declare numbers using underscore characters to make them more readable:
val a = 1_000 // Int
val b = 1_000_000 // Int
val c = 1_000_000L // Long (created with the 'L' after the number)
val d = 1_234.56 // Double
This is a really useful feature when you’re working with large numbers.
BigInt and BigDecimal
When you need to create really, really large numbers, use the BigInt
and BigDecimal
data types:
val a = BigInt(1_234_567_890_123_456L)
val b = BigDecimal(123_456_789.012)
Use BigInt
when you need integer-type numbers that are larger than Long
, and BigDecimal
when using very large floating-point numbers. Some developers also use BigDecimal
for working with currency.
Scala data type sizes
For your reference, this table provides details about Scala’s data types:
Data Type Definition
Boolean true or false
Byte 8-bit signed two’s complement integer
(-2^7 to 2^7-1, inclusive)
-128 to 127
Short 16-bit signed two’s complement integer
(-2^15 to 2^15-1, inclusive)
-32,768 to 32,767
Int 32-bit two’s complement integer
(-2^31 to 2^31-1, inclusive)
-2,147,483,648 to 2,147,483,647
Long 64-bit two’s complement integer
(-2^63 to 2^63-1, inclusive)
-9,223,372,036,854,775,808 to +9,223,372,036,854,775,807
Float 32-bit IEEE 754 single-precision float
1.40129846432481707e-45 to 3.40282346638528860e+38
(positive or negative)
Double 64-bit IEEE 754 double-precision float
4.94065645841246544e-324 to 1.79769313486231570e+308
(positive or negative)
Char 16-bit unsigned Unicode character
(0 to 2^16-1, inclusive)
0 to 65,535
String a sequence of Char values
For more details on BigInt
and BigDecimal
, see their Scaladoc pages:
this post is sponsored by my books: | |||
#1 New Release |
FP Best Seller |
Learn Scala 3 |
Learn FP Fast |
Exercises
The exercises for this lesson are available here.