Range 是 Scala 中一个常用的特性,具有以下特点:
- 支持 to 及 until,to 包含边界上限,until 不包含边界上限(两者均包含边界下限)
- 支持 Int、Long、Float、Double、Char、BigInt、BigDecimal
- 支持自定义步长及默认步长
接下来我们通过几个例子来加深对这几个特性的印象
支持 to 及 until
scala> 1 to 10
res2: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
scala> 1 until 10
res3: scala.collection.immutable.Range = Range(1, 2, 3, 4, 5, 6, 7, 8, 9)
支持多种数据类型
Int
scala> 1 to 5
res11: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5)
scala> 1 to 5 by 2
res12: scala.collection.immutable.Range = Range(1, 3, 5)
scala> 1 to 5 by 3
res13: scala.collection.immutable.Range = Range(1, 4)
Long
scala> 1L to 5L
res14: scala.collection.immutable.NumericRange.Inclusive[Long] = NumericRange(1, 2, 3, 4, 5)
scala> 1L to 5L by 2
res15: scala.collection.immutable.NumericRange[Long] = NumericRange(1, 3, 5)
scala> 1L to 5L by 2L
res16: scala.collection.immutable.NumericRange[Long] = NumericRange(1, 3, 5)
scala> 1L to 5L by 3L
res17: scala.collection.immutable.NumericRange[Long] = NumericRange(1, 4)
Float
scala> 1.0F to 5.0F by 1.0F
res9: scala.collection.immutable.NumericRange[Float] = NumericRange(1.0, 2.0, 3.0, 4.0, 5.0)
scala> 1.0F to 5.0F by 1.3F
res10: scala.collection.immutable.NumericRange[Float] = NumericRange(1.0, 2.3, 3.6, 4.8999996)
Double
scala> 1.0D to 5.0D by 1.0D
res24: scala.collection.immutable.NumericRange[Double] = NumericRange(1.0, 2.0, 3.0, 4.0, 5.0)
scala> 1.0D to 5.0D by 1.3D
res25: scala.collection.immutable.NumericRange[Double] = NumericRange(1.0, 2.3, 3.5999999999999996, 4.8999999999999995)
Char
scala> 'a' to 'e' by 1
res26: scala.collection.immutable.NumericRange[Char] = NumericRange(a, b, c, d, e)
scala> 'a' to 'e' by 2
res27: scala.collection.immutable.NumericRange[Char] = NumericRange(a, c, e)
BigInt
scala> BigInt(1) to BigInt(5)
res36: scala.collection.immutable.NumericRange.Inclusive[BigInt] = NumericRange(1, 2, 3, 4, 5)
scala> BigInt(1) to BigInt(5) by 2
res38: scala.collection.immutable.NumericRange[BigInt] = NumericRange(1, 3, 5)
BigDecimal
scala> BigDecimal(1.1) to BigDecimal(5.6) by 1.3
res41: scala.collection.immutable.NumericRange.Inclusive[scala.math.BigDecimal] = NumericRange(1.1, 2.4, 3.7, 5.0)
scala> BigDecimal(1.1) to BigDecimal(5.6) by 3.3
res42: scala.collection.immutable.NumericRange.Inclusive[scala.math.BigDecimal] = NumericRange(1.1, 4.4)
支持自定义步长及默认步长
在上一小节的很多例子中,都用 by 指定了自定义步长,所有的类型都支持指定自定义步长。但并不是所有的类型都有默认步长,只有以下类型具有默认步长:
- Int默认步长: 1
- Long默认步长: 1
- Char默认步长: 1
- BigInt默认步长: 1