Skip to content

Commit d4852dc

Browse files
author
Martijn Hoekstra
committed
move safe last impl to TraversableViewLike
also align with lastOption impl in terms of empty/hasElements
1 parent 0ee8875 commit d4852dc

File tree

2 files changed

+15
-6
lines changed

2 files changed

+15
-6
lines changed

src/library/scala/collection/TraversableLike.scala

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -428,13 +428,10 @@ trait TraversableLike[+A, +Repr] extends Any
428428
* @throws NoSuchElementException If the $coll is empty.
429429
*/
430430
def last: A = {
431-
var lst: A = null.asInstanceOf[A]
432-
var hasElements = false
433-
for (x <- this){
434-
hasElements = true
431+
var lst = head
432+
for (x <- this)
435433
lst = x
436-
}
437-
if (hasElements) lst else throw new NoSuchElementException("last of empty traversable")
434+
lst
438435
}
439436

440437
/** Optionally selects the last element.

src/library/scala/collection/TraversableViewLike.scala

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,18 @@ trait TraversableViewLike[+A,
112112

113113
None
114114
}
115+
116+
override def last: B = {
117+
// (Should be) better than allocating a Some for every element.
118+
var empty = true
119+
var result: B = null.asInstanceOf[B]
120+
for (x <- this) {
121+
empty = false
122+
result = x
123+
}
124+
if (empty) throw new NoSuchElementException("last of empty traversable") else result
125+
}
126+
115127
override def lastOption: Option[B] = {
116128
// (Should be) better than allocating a Some for every element.
117129
var empty = true

0 commit comments

Comments
 (0)