在交互式scala控制台中运行以下代码
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")
Run Code Online (Sandbox Code Playgroud)
返回以下内容
Test 5 null null null
Run Code Online (Sandbox Code Playgroud)
我希望这个代码在第一次调用之外的所有调用中都会导致调用get方法的错误参数数量的编译器错误.为什么这个成功编译并返回null?
0__*_*0__ 12
Java映射不是类型安全的,特别是该get方法具有以下签名:
public V get(Object key);
Run Code Online (Sandbox Code Playgroud)
所以你可以用任何东西作为钥匙.在Scala中,您会看到所谓的自动翻译,这在Scala 2.11中已被弃用,所以如果使用编译项目-deprecation,您会看到:
[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] ^
Run Code Online (Sandbox Code Playgroud)
您可以使用-Xfuture编译器标志将其转换为错误:
[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] ^
Run Code Online (Sandbox Code Playgroud)
自动几倍手段map.get()将被视为map.get(())和map.get("key1", "key2")将被视为map.get(("key1", "key2")).
我建议使用Scala自己的集合类型,除非您有非特别的理由不这样做.
| 归档时间: |
|
| 查看次数: |
168 次 |
| 最近记录: |