给出以下
scala代码:
val mapAll= Map("A"-> 1.toShort,"B"-> 2.toShort) val map1 = Map("A"-> 1.toShort) val map2 = mapAll.map(x => (x._2,map1.getOrElse(x._1,-1.toShort)))
在这种情况下,IDEA中显示的map2的类型是Map [Short,Int].
我需要的是Map [Short,Short]
但是,如果将-1放入“()”这样的话“
val map2 = mapAll.map(x => (x._2,(-1).toShort)))
没关系. IDEA中显示的map2的类型是Map [Short,Short]
那么,“( – 1).toShort”和“-1.toShort”之间有什么区别
解决方法
没有区别.在这种情况下,你可能会被IntelliJ的糟糕类型推断所欺骗.使用-Xprint:typer标志编译scalac时可以看到这一点:
val map2: scala.collection.immutable.Map[Short,Short] = mapAll.map[(Short,Short),scala.collection.immutable.Map[Short,Short]]( ((x: (String,Short)) => scala.Tuple2.apply[Short,Short]( x._2,map1.getOrElse[Short](x._1,-1.toShort)))) (immutable.this.Map.canBuildFrom[Short,Short]);
我们还可以通过简化示例来验证这一点:
val shortOne = -1.toShort val shortTwo = (-1).toShort
并使用-Xprint:jvm进行编译以查看最终发出的步骤:
val shortOne: Short = -1.toShort(); val shortTwo: Short = -1.toShort();
你可以看到两者是相同的.