Article Directory
In Scala, Range
an immutable sequence used to represent a sequence of consecutive integer values. Range
Can be used to iterate over a set of integers or generate a sequence of integers in set operations.
1. Define Range
Range
There are three ways to define:
1. Use the to method
val range1 = 1 to 5 // 表示从 1 到 5(包含 1 和 5),步长为 1
2. Use the until method
val range2 = 1 until 5 // 表示从 1 到 5(不包含 5),步长为 1
3. Use the by method to specify the step size
val range3 = 1 to 10 by 2 // 表示从 1 到 10(包含 1 和 10),步长为 2
Two, Range companion object
A Scala Range
class is created through a companion object (Companion Object), which is an object with the same name as the class and defined in the same source file. Companion objects and classes share the same namespace and can access each other's private members. In Scala, companion objects are often used to define class factory methods, static members, and other shared functionality related to the class.
Range
The companion object of can be used to create Range
instances, which can be apply
created by calling the method of the companion object Range
. Range
The companion object of provides multiple overloaded apply
methods for different creation methods.
Range
Here is an example of creating an instance using a companion object Range
:
// 使用伴生对象的 apply 方法创建 Range
val range1 = Range(1, 5) // 表示从 1 到 5(包含 1 和 5),步长为 1
val range2 = Range(1, 10, 2) // 表示从 1 到 10(包含 1 和 10),步长为 2
// 使用伴生对象的 from 和 to 方法创建 Range
val range3 = Range.from(1) // 表示从 1 开始的无限整数序列
val range4 = Range.to(5) // 表示从 0 到 4(包含 0 和 4),步长为 1
// 使用伴生对象的 in方法创建 Range
val range5 = Range.inclusive(1, 5) // 表示从 1 到 5(包含 1 和 5),步长为 1
// 遍历 Range 的元素
range1.foreach(println) // Output: 1 2 3 4 5
range2.foreach(println) // Output: 1 3 5 7 9
range3.take(5).foreach(println) // Output: 1 2 3 4 5
range4.foreach(println) // Output: 0 1 2 3 4
range5.foreach(println) // Output: 1 2 3 4 5
In the example above, we used Range
different methods of the companion object to create Range
instances and iterate over Range
the elements of the . Creating an instance using a companion object Range
is a more concise and convenient way, especially when defining a sequence of integers with a large range, which can avoid explicitly creating a collection containing all elements.
Three, traverse the Range
In Scala, there are several ways to iterate Range
. Range
Can be seen as a sequence of integers, so the elements can be traversed using common set operations or loop constructs.
Here are several Range
ways to traverse the :
- Use the foreach method:
val range = 1 to 5
range.foreach(println)
- Use a for loop:
val range = 1 to 5
for (num <- range) {
println(num)
}
Traversal Range
can use foreach
the method, for
loop or other common collection operation methods, which method to use depends on the needs and personal habits.