TheDeveloperBlog.com

Home | Contact Us

CSharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript

<< Back to SCALA

Scala Int Examples: Max and Min

Use Int values and numeric functions like max and min. Call to and until.
Int. An Int is 5, 10, 15. In 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.

Max: With max, we compare 2 numbers. The higher number is returned. So our result is always the higher one.

Min: This returns the lower of the 2 numbers. Negative numbers are supported. Only one number is returned—it is always the lower one.

Scala program that uses max, min 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) Output 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.ForConsole

So: With "to" we have an inclusive range, and with "until" we have an exclusive end to our range.

Range
Scala program that uses Int to, until 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) } Output 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.
© TheDeveloperBlog.com
The Dev Codes