Reputation: 83
Running the following code in an interactive scala console
val map = new java.util.HashMap[String, Integer]();
map.put("key1", 5)
"Test " + map.get("key1") + " " + map.get() + " " + map.get("key1", "key2") + " " + map.get("key1", "key2", "key3")
returns the following
Test 5 null null null
I would expect this code to result in a compiler error about the wrong number of parameters in the call to the get method in all but the first call. Why is this successfully compiling and just returning null?
Upvotes: 8
Views: 193
Reputation: 67310
The Java map is not type safe, in particular the get
method has this signature:
public V get(Object key);
So you can use anything as a key. In Scala you are seeing so-called auto-tupling, something that is deprecated in Scala 2.11, so if you compile your project with -deprecation
, you will see:
[warn] ... Adaptation of argument list by inserting () has been deprecated: leaky (Object-receiving) target makes this especially dangerous.
[warn] signature: HashMap.get(x$1: Any): V
[warn] given arguments: <none>
[warn] after adaptation: HashMap.get((): Unit)
[warn] "Test " + map.get("key1") + " " + map.get() + " " + map.get("key1", "key2") + " " + map.get("key1", "key2", "key3")
[warn] ^
You can turn that into an error with the -Xfuture
compiler flag:
[error] ... Adaptation of argument list by inserting () has been removed.
[error] signature: HashMap.get(x$1: Any): V
[error] given arguments: <none>
[error] "Test " + map.get("key1") + " " + map.get() + " " + map.get("key1", "key2") + " " + map.get("key1", "key2", "key3")
[error] ^
Auto-tupling means map.get()
will be treated as map.get(())
and map.get("key1", "key2")
will be treated as map.get(("key1", "key2"))
.
I recommend using Scala's own collection types unless you have a very particular reason not to do so.
Upvotes: 12