简体   繁体   中英

scala new Range with step equals zero

Is(and why) this really should be prohibited with exception?

scala> val r2 = 15 until (10, 0)

java.lang.IllegalArgumentException: requirement failed

scala> new Range(10,15,0)

java.lang.IllegalArgumentException: requirement failed
    at scala.Predef$.require(Predef.scala:133)

Is(and why) this really should be prohibited with exception?

Quoting from scaladoc :

The Range class represents integer values in range [start;end) with non-zero step value step. Sort of acts like a sequence also (supports length and contains).

This restriction makes sense. A range with step-size zero would always be infine and just consist of the lower bound value. Whereas one could argue that infinite ranges are possible (lazy evaluation), the concept of an upper bound in the range would be taken ad absurdum. A range with step 0 is simply not a range , even if it's infinitely long, because the upper bound has no importance.

So if one really wants an infinite stream of a single value, Scala rightfully forces us to be more explicit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM