Sometimes we need a sequence of numbers from some start to finish. A Range literal is just what we need. The following examples show how to create ranges for the types that support them, Int
, Long
, Float
, Double
, Char
, BigInt
(which represents integers of arbitrary size), and BigDecimal
(which represents floating-point numbers of arbitrary size).
You can create ranges with an inclusive or exclusive upper bound, and you can specify an interval not equal to one:
scala> 1 to 10 // Int range inclusive, interval of 1, (1 to 10)
res0: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
scala> 1 until 10 // Int range exclusive, interval of 1, (1 to 9)
res1: scala.collection.immutable.Range = Range(1, 2, 3, 4, 5, 6, 7, 8, 9)
scala> 1 to 10 by 3 // Int range inclusive, every third.
res2: scala.collection.immutable.Range = Range(1, 4, 7, 10)
scala> 10 to 1 by -3 // Int range inclusive, every third, counting down.
res2: scala.collection.immutable.Range = Range(10, 7, 4, 1)
scala> 1L to 10L by 3 // Long
res3: scala.collection.immutable.NumericRange[Long] = NumericRange(1, 4, 7, 10)
scala> 1.1f to 10.3f by 3.1f // Float with an interval != 1
res4: scala.collection.immutable.NumericRange[Float] =
NumericRange(1.1, 4.2, 7.2999997)
scala> 1.1f to 10.3f by 0.5f // Float with an interval < 1
res5: scala.collection.immutable.NumericRange[Float] =
NumericRange(1.1, 1.6, 2.1, 2.6, 3.1, 3.6, 4.1, 4.6, 5.1, 5.6, 6.1, 6.6,
7.1, 7.6, 8.1, 8.6, 9.1, 9.6, 10.1)
scala> 1.1 to 10.3 by 3.1 // Double
res6: scala.collection.immutable.NumericRange[Double] =
NumericRange(1.1, 4.2, 7.300000000000001)
scala> 'a' to 'g' by 3 // Char
res7: scala.collection.immutable.NumericRange[Char] = NumericRange(a, d, g)
scala> BigInt(1) to BigInt(10) by 3
res8: scala.collection.immutable.NumericRange[BigInt] = NumericRange(1, 4, 7, 10)
scala> BigDecimal(1.1) to BigDecimal(10.3) by 3.1
res9: scala.collection.immutable.NumericRange.Inclusive[scala.math.BigDecimal] = NumericRange(1.1, 4.2, 7.3)
Ref