Int Examples: Max and MinUse Int values and numeric functions like max and min. Call to and until.
Scala
Int. Think of some numbers: 5, 10, 15. In Scala programs we use integers in everything. We use them to access list and arrays. 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.
Initial example. 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.
Info With max, we compare 2 numbers. The higher number is returned. So our result is always the higher one.
And Min returns the lower of the 2 numbers. Negative numbers are supported. Only one number is returned—it is always the lower one.
val number = 10 // Compute max of these numbers. val result1 = number.max(20) val result2 = number.max(0) println("10 max 20 = " + result1) println("10 max 0 = " + result2) // Compute min of these numbers. val result3 = number.min(5) val result4 = number.min(500) println("10 min 5 = " + result3) println("10 min 500 = " + result4)
10 max 20 = 20 10 max 0 = 10 10 min 5 = 5 10 min 500 = 10
To, until. 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.
for
println
So With "to" we have an inclusive range, and with "until" we have an exclusive end to our range.
Range
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, 11, 12, 13, 14, 15) 10 11 12 13 14 15 Range(5, 6, 7, 8, 9) 5 6 7 8 9
Odd, even. 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.
Odd, Even
A summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.