Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

IndexedSeq#head now throws NoSuchElementException (not IndexOutOfBoundsException) #10392

Merged
merged 2 commits into from
Jun 23, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
IndexedSeq.head uses isEmpty
Seq.isEmpty is lengthCompare and IndexedSeq
has efficient length aka knownSize. headOption
already uses isEmpty.
  • Loading branch information
som-snytt committed May 4, 2023
commit f3c5026d3bbb68a25f0f21748970e72a554c7001
32 changes: 14 additions & 18 deletions src/library/scala/collection/IndexedSeq.scala
Original file line number Diff line number Diff line change
Expand Up @@ -92,28 +92,24 @@ trait IndexedSeqOps[+A, +CC[_], +C] extends Any with SeqOps[A, CC, C] { self =>
override def slice(from: Int, until: Int): C = fromSpecific(new IndexedSeqView.Slice(this, from, until))

override def head: A =

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wouldn't this now lead to repeated checks for isEmpty in {head,last}Option? should there be an @inline def headImpl: A = apply(0) and used in both head and headOption?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My comment on the first commit is that head is fast. headOption is allocating.

try apply(0)
catch {
case e: IndexOutOfBoundsException =>
val what = self match {
case self: IndexedSeq[_] => self.collectionClassName
case _ => toString
}
throw new NoSuchElementException(s"head of empty $what")
}
if (!isEmpty) apply(0)
else throw new NoSuchElementException(s"head of empty ${
self match {
case self: IndexedSeq[_] => self.collectionClassName
case _ => toString
}
}")

override def headOption: Option[A] = if (isEmpty) None else Some(head)

override def last: A =
try apply(length - 1)
catch {
case e: IndexOutOfBoundsException =>
val what = self match {
case self: IndexedSeq[_] => self.collectionClassName
case _ => toString
}
throw new NoSuchElementException(s"last of empty $what")
}
if (!isEmpty) apply(length - 1)
else throw new NoSuchElementException(s"last of empty ${
self match {
case self: IndexedSeq[_] => self.collectionClassName
case _ => toString
}
}")

// We already inherit an efficient `lastOption = if (isEmpty) None else Some(last)`

Expand Down