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 f开发者_StackOverflow中文版ailed
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.
精彩评论