Thomas Böhm Thomas Böhm -4 years ago 87
Scala Question

Why is map.get with 2 parameters possible?

I have 2 maps,

map1
and
map2
, both of type
Map[String, MyType]
.

What I wanted to do was, searching for a key in the first map, if not found, search in the second one, and if still not found, use a default value:

map1.getOrElse(name, map2.getOrElse(name, defVal))


However, what I accidently wrote was:

map1.getOrElse(name, map2.get(name, defVal))
.

Surprisingly, this didn't cause a compile-time error (and returned
null
), although i called
get
with 2 parameters.

As I can see in the IDE (Eclipse), it calls
get(x$1 : Any) : MyType
of
java.util.Map
, instead of
get(key : String) : Option[MyType]
of
scala.collection.MapLike


Why doesn't it report an error, when I call
map2.get
with a second parameter? As far as I can see in the documentation,
map.get
only takes one parameter? Does it interpret the two parameters as a tuple or something similar (and use this tuple as
Any
-parameter)?

If relevant,
MyType
is a class from a referenced
Java
-project.

I am quiet new in Scala, so if this is trivial or a basic concept that I missed (and everyone programming scala should already know), please tell me what to search for.

EDIT:

As I saw in the comments, that the problem is not reproduceable, I saw, that I hava
import scala.collection.javaConversions._
, because I get the collections from a Java-Project that I reference. Now it is also reproducable with a short code like this:

import scala.collection.JavaConversions._
object Main {
def main (args : Array[String]) : Unit = {
val map1 = Map("1" -> 2)
val map2 = Map("2" -> 1)
map1.getOrElse("1", map2.get("2", 0))
}
}

Answer Source

Might be argument adaptation from map2.get(name, defVal) to map2.get((name, defVal)).

Edit: Use JavaConverters. JavaConversions is deprecated.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download