Skip to content

Commit 4c52b44

Browse files
committed
Translate outbound IndexOutOfBounds in IndexedSeq.head
1 parent e932f9c commit 4c52b44

File tree

1 file changed

+20
-2
lines changed

1 file changed

+20
-2
lines changed

library/src/scala/collection/IndexedSeq.scala

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -91,11 +91,29 @@ trait IndexedSeqOps[+A, +CC[_], +C] extends Any with SeqOps[A, CC, C] { self =>
9191

9292
override def slice(from: Int, until: Int): C = fromSpecific(new IndexedSeqView.Slice(this, from, until))
9393

94-
override def head: A = apply(0)
94+
override def head: A =
95+
try apply(0)
96+
catch {
97+
case e: IndexOutOfBoundsException =>
98+
val what = self match {
99+
case self: IndexedSeq[_] => self.collectionClassName
100+
case _ => toString
101+
}
102+
throw new NoSuchElementException(s"head of empty $what")
103+
}
95104

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

98-
override def last: A = apply(length - 1)
107+
override def last: A =
108+
try apply(length - 1)
109+
catch {
110+
case e: IndexOutOfBoundsException =>
111+
val what = self match {
112+
case self: IndexedSeq[_] => self.collectionClassName
113+
case _ => toString
114+
}
115+
throw new NoSuchElementException(s"last of empty $what")
116+
}
99117

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

0 commit comments

Comments
 (0)