On the empty string, .tail and .init now throw (instead of returning the empty string)#10851
Conversation
| * @throws NoSuchElementException if the string is empty. | ||
| * @note $unicodeunaware | ||
| */ | ||
| def tail: String = if(s.isEmpty) throw new NoSuchElementException("tail of empty String") else slice(1, s.length) |
There was a problem hiding this comment.
Most collections follow IterableOps in throwing UnsupportedOperation (but NSE for head and last).
A couple deviate and throw NSE. It's fine to leave it as it is here.
Example showing difficulty of enforcing uniformity of behavior:
scala> 0.until(0).tail
java.util.NoSuchElementException: tail on empty Range
at scala.collection.immutable.Range$.scala$collection$immutable$Range$$emptyRangeError(Range.scala:631)
at scala.collection.immutable.Range.tail(Range.scala:144)
... 30 elided
scala> 0.to(0).tail
val res4: scala.collection.immutable.Range = empty Range 0 until 0
example with descriptive message:
scala> collection.immutable.ArraySeq(Array(42)).tail.tail
java.lang.UnsupportedOperationException: tail of empty array
at scala.collection.ArrayOps$.tail$extension(ArrayOps.scala:346)
at scala.collection.immutable.ArraySeq.tail(ArraySeq.scala:242)
... 30 elided
There was a problem hiding this comment.
I meant to add, I'll merge as-is if you don't change it. Merges are paused until 2.13.15 is released, I assume.
| * @throws NoSuchElementException if the string is empty. | ||
| * @note $unicodeunaware | ||
| */ | ||
| def tail: String = if(s.isEmpty) throw new NoSuchElementException("tail of empty String") else slice(1, s.length) |
There was a problem hiding this comment.
I meant to add, I'll merge as-is if you don't change it. Merges are paused until 2.13.15 is released, I assume.
Philippus
left a comment
There was a problem hiding this comment.
most "of empty" exceptions lowercase the type, e.g. "tail of empty array" / "tail of empty list". Would be nice to keep that consistent and use "tail of empty string" / "init of empty string".
|
Nice observation. Exception as shown is I always have a hiccup on String vs string, and favor String FSR. I would probably prefer naming a type, |
26442d9 to
0e088bc
Compare
|
It is rather bewildering trying to figure out what the "right" or "best" exception to throw is here, but I'll go along with the I have taken the liberty of squashing and force-pushing, so we can hit merge as soon as CI likes it. I will release-note this since it wouldn't surprise me if there is code out there inadvertently relying on the old behavior. |
som-snytt
left a comment
There was a problem hiding this comment.
I merged on Seth's approval, but normally I would have complained that there is no space after if.
.tail and .init now throw (instead of returning the empty string)
…y-string Throw exception on tail init when empty string
…y-string Throw exception on tail init when empty string
fix scala/bug#13026