Int
Think of some numbers: 5, 10, 15. In Scala 3.3 programs we use integers in everything. We use them to access list and arrays, and we use them to test data.
With helpful functions, we use Int
values in a more efficient, clearer way. In Scala we invoke functions like max and min, to and until to handle numbers and ranges.
Here we use a constant Int
called "number." We set it to the value 10. We then invoke max and min on this number, comparing it to others.
Min
returns the lower of the 2 numbers. Negative numbers are supported. Only one number is returned—it is always the lower one.object Program { def main(args: Array[String]): Unit = { val number = 10 // Compute max of these numbers. val result1 = number.max(20) val result2 = number.max(0) println(s"10 max 20 = $result1") println(s"10 max 0 = $result2") // Compute min of these numbers. val result3 = number.min(5) val result4 = number.min(500) println(s"10 min 5 = $result3") println(s"10 min 500 = $result4") } }10 max 20 = 20 10 max 0 = 10 10 min 5 = 5 10 min 500 = 10
With Ints, we can generate ranges in Scala. The "to" and "until" functions are useful here. They both do a similar thing, but until does not include the argument in the range.
object Program { def main(args: Array[String]): Unit = { val number = 10 // Get range from 10 to 15 inclusive. val result = number.to(15) println(result) // Print all elements in the range. for (element <- result) { println(element) } // Get range from 5 (inclusive) to 10 (exclusive). // ... The argument is not included in the range. val result2 = 5.until(10) println(result2) // Print elements. for (element <- result2) { println(element) } } }Range 10 to 15 10 11 12 13 14 15 Range 5 until 10 5 6 7 8 9
An integer is odd or even. This is its parity. In Scala we can compute parity with modulo division, and even generated filtered sequences of even or odd numbers.
Integers are an important data type. In Scala we work with built-in abstractions to handle Ints. These simplify our programs. They clarify our logic and help make it correct.