Numbers

Scala has the numeric types of the JVM — Int, Long, Short, Byte, Float, Double — and two arbitrary-precision types of its standard library, BigInt and BigDecimal. The types are the ones Java has; the literals, the operators and the conversions are Scala's, and the differences are what this lesson shows.

Integer division and overflow

An Int literal is an Int, so division of two of them is integer division, and the result of an operation that leaves the range is the wrapped value rather than an exception:

numbers.scala

@main def numbers(): Unit = println(7 / 2) println(7 % 2) println(7.0 / 2) println(Int.MaxValue + 1) println(1_000_000) println(0xff) println(2e3)

scala-cli run --server=false numbers.scala

3
1
3.5
-2147483648
1000000
255
2000.0

7 / 2 is 3, and 7.0 / 2 is 3.5: one operand of a floating type is enough. Int.MaxValue + 1 wraps to the smallest Int without a word, exactly as Java does, which is why a sum that can grow is a Long or a BigInt. The underscore in 1_000_000 is a digit separator, 0xff is hexadecimal, and 2e3 is a Double of 2000.

BigInt and BigDecimal

The standard library has two types without a limit. BigInt is an arbitrary-precision integer and BigDecimal a decimal with a fixed number of digits that a division can round:

big.scala

@main def big(): Unit = val factorial = (1 to 20).map(BigInt(_)).product println(factorial) val price = BigDecimal("19.99") val quantity = BigDecimal(3) println(price * quantity) println(BigDecimal(1) / BigDecimal(3)) println(f"${(price * quantity).toDouble}%.2f")

scala-cli run --server=false big.scala

2432902008176640000
59.97
0.3333333333333333333333333333333333
59.97

20! does not fit in a Long, and BigInt prints every digit. BigDecimal(1) / BigDecimal(3) stops at the thirty-four digits of the default MathContext, so the last digit is a rounded one; money is the reason the type exists, and a format string turns it back into two decimals at the edge of the program.

Conversion and parsing

A conversion widens by itself and narrows only when it is asked. Parsing a string is a conversion too, and Scala 3 offers an Option version that does not throw:

convert.scala

@main def convert(): Unit = println("42".toInt) println("3.5".toDouble) println(42.toString) println(255.toHexString) println("not a number".toIntOption)

scala-cli run --server=false convert.scala

42
3.5
42
ff
None

"42".toInt throws NumberFormatException on a string that is not a number, and toIntOption answers None instead, which is the form a program that expects bad input uses. The Option lesson takes the type apart; toDouble has a toDoubleOption beside it, and toLong, toBigInt and toBoolean follow the same pair.

Related

Article author: Arthur Isaev