对于没有类型声明的List,Scala会查看所有元素并尝试查找常用类型。在你的情况下,由于Int可以转换为Double,它会将混合列表转换为一个List [Double]来提升你的一个Int。
Map构造函数需要一系列2元组。你会得到相同的行为,如果你只是构造元组的列表:
scala> List((1, "one"), (2.0, "two.oh"))
res0: List[(AnyVal, String)] = List((1,one), (2.0,two.oh))
Tuple2 [诠释,字符串]不能自动晋升为Tuple2 [双,字符串。在这种情况下,你需要帮助编译器了一点与类型声明:
scala> val x: List[(Double, String)] = List((1, "one"), (2.0, "two.oh"))
x: List[(Double, String)] = List((1.0,one), (2.0,two.oh))
或
scala> val x = List[(Double, String)]((1, "one"), (2.0, "two.oh"))
x: List[(Double, String)] = List((1.0,one), (2.0,two.oh))
或在您的情况:
scala> val x = List[(Double, String)]((1, "one"), (2.0, "two.oh")).toMap
x: scala.collection.immutable.Map[Double,String] = Map(1.0 -> one, 2.0 -> two.oh)
出于某种原因,在Map上使用类型声明不起作用。不知道为什么:
scala> val x = Map[Double, String](1 -> "one", 2.0 -> "two.oh")
<console>:7: error: type mismatch;
found : (Int, String)
required: (Double, String)
val x = Map[Double, String](1 -> "one", 2.0 -> "two.oh")
可以在2.9.2上重现。 –