Skip to content

Commit 7b425bf

Browse files
committed
SI-6370 changed ListMap apply0 method to produce correct error message when a key is not found
Current implementation of apply0 relies on tail method to iterate over all keys. When the list gets to its end, tail produces an 'empty map' message in its exception, which is thrown by ListMap. This change checks if the collection is empty before calling tail and provides a more appropriate key not found message. Signed-off-by: Vinicius Miana <[email protected]>
1 parent 1a63cf8 commit 7b425bf

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

src/library/scala/collection/immutable/ListMap.scala

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -156,8 +156,12 @@ extends AbstractMap[A, B]
156156
* @return the value associated with the given key.
157157
*/
158158
override def apply(k: A): B1 = apply0(this, k)
159-
160-
@tailrec private def apply0(cur: ListMap[A, B1], k: A): B1 = if (k == cur.key) cur.value else apply0(cur.tail, k)
159+
160+
161+
@tailrec private def apply0(cur: ListMap[A, B1], k: A): B1 =
162+
if (cur.isEmpty) throw new NoSuchElementException("key not found: "+k)
163+
else if (k == cur.key) cur.value
164+
else apply0(cur.tail, k)
161165

162166
/** Checks if this map maps `key` to a value and return the
163167
* value if it exists.

test/files/run/t6370.scala

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
object Test {
2+
3+
def main(args: Array[String]): Unit = {
4+
val m = collection.immutable.ListMap( "x" -> 1 )
5+
try {
6+
m("y")
7+
} catch {
8+
case e : NoSuchElementException => assert(e.getMessage() == "key not found: y")
9+
}
10+
11+
}
12+
}

0 commit comments

Comments
 (0)