bug
bug copied to clipboard
Empty string tail and init don't throw (unlike WrappedString)
Reproduction steps
Scala version: 2.13.14
scala> "".tail
val res0: String = ""
scala> "".init
val res1: String = ""
scala> def tailOf[A](x: Seq[A]) = x.tail
def tailOf[A](x: Seq[A]): Seq[A]
scala> tailOf("")
java.lang.UnsupportedOperationException
at scala.collection.IterableOps.tail(Iterable.scala:528)
at scala.collection.IterableOps.tail$(Iterable.scala:527)
at scala.collection.AbstractIterable.tail(Iterable.scala:935)
at tailOf(<console>:1)
... 32 elided
scala> def initOf[A](x: Seq[A]) = x.init
def initOf[A](x: Seq[A]): Seq[A]
scala> initOf("")
java.lang.UnsupportedOperationException
at scala.collection.IterableOps.init(Iterable.scala:536)
at scala.collection.IterableOps.init$(Iterable.scala:535)
at scala.collection.AbstractIterable.init(Iterable.scala:935)
at initOf(<console>:1)
... 32 elided
Problem
I guess I expected them to be consistent with other collections and throw when empty.
I agree. It's checked everywhere, even with tail in terms of drop in terms of slice, where slice is forgiving about index out of bounds.
We'd have noticed this sooner, if only we used more strings when coding.
fyi @scala/collections
We have a PR! My idea was to have a scalacheck that checks uniformity of behavior of collections API. That is in lieu of touching collection-laws, which I looked at again. The idea is merely to verify that init has uniform behavior (and throws the same exception, for example) with a model or prototype collection, such as List. Maybe there is a prototype for Seq, Set, Map, and mutable vs immutable.