scala / bug

Scala 2 bug reports only. Please, no questions — proper bug reports only.
https://scala-lang.org
232 stars 21 forks source link

Empty string tail and init don't throw (unlike WrappedString) #13026

Open joroKr21 opened 2 months ago

joroKr21 commented 2 months ago

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.

som-snytt commented 2 months ago

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.

SethTisue commented 2 months ago

fyi @scala/collections

som-snytt commented 2 months ago

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.