bug icon indicating copy to clipboard operation
bug copied to clipboard

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

Open joroKr21 opened this issue 1 year ago • 3 comments

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.

joroKr21 avatar Aug 28 '24 14:08 joroKr21

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.

som-snytt avatar Aug 28 '24 16:08 som-snytt

fyi @scala/collections

SethTisue avatar Aug 29 '24 11:08 SethTisue

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.

som-snytt avatar Aug 31 '24 17:08 som-snytt