[Scala Collection] 15. Immutable sequence Range

insert image description here

In Scala, Rangean immutable sequence used to represent a sequence of consecutive integer values. RangeCan be used to iterate over a set of integers or generate a sequence of integers in set operations.

1. Define Range

RangeThere 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 Rangeclass 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.

RangeThe companion object of can be used to create Rangeinstances, which can be applycreated by calling the method of the companion object Range. RangeThe companion object of provides multiple overloaded applymethods for different creation methods.

RangeHere 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 Rangedifferent methods of the companion object to create Rangeinstances and iterate over Rangethe elements of the . Creating an instance using a companion object Rangeis 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. RangeCan be seen as a sequence of integers, so the elements can be traversed using common set operations or loop constructs.

Here are several Rangeways to traverse the :

  1. Use the foreach method:
val range = 1 to 5
range.foreach(println)
  1. Use a for loop:
val range = 1 to 5
for (num <- range) {
    
    
  println(num)
}

Traversal Rangecan use foreachthe method, forloop or other common collection operation methods, which method to use depends on the needs and personal habits.

おすすめ

転載: blog.csdn.net/m0_47256162/article/details/132159775