Skip to content

Commit b0caf0f

Browse files
authored
Merge pull request scala/scala#10392 from som-snytt/issue/12782-head
IndexedSeq.head throws NoSuchElementException
2 parents 49835f4 + 78da69f commit b0caf0f

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

library/src/scala/collection/IndexedSeq.scala

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -91,11 +91,25 @@ 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+
if (!isEmpty) apply(0)
96+
else throw new NoSuchElementException(s"head of empty ${
97+
self match {
98+
case self: IndexedSeq[_] => self.collectionClassName
99+
case _ => toString
100+
}
101+
}")
95102

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

98-
override def last: A = apply(length - 1)
105+
override def last: A =
106+
if (!isEmpty) apply(length - 1)
107+
else throw new NoSuchElementException(s"last of empty ${
108+
self match {
109+
case self: IndexedSeq[_] => self.collectionClassName
110+
case _ => toString
111+
}
112+
}")
99113

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

0 commit comments

Comments
 (0)