为什么Scala REPL显示Map表达式的元组类型? [英] Why Scala REPL shows tuple type for Map expression?
问题描述
Scala REPL为两个表达式提供相同的类型 - (tuple? - 奇怪!)。然而,(a - > 1)
这是我可以添加到地图的地图和(a,1)
不能。为什么Scala REPL显示地图表达式的元组类型?
scala> :t(a - > 1)
/ pre>
(String,Int)
scala> :t(a,1)
(String,Int)
scala> val m = Map.empty [String,Int]
m:scala.collection.immutable.Map [String,Int] = Map()
scala> m +(a,1)
< console>:9:error:type mismatch;
found:String(a)
required:(String,?)
m +(a,1)
^
scala> m +(a - > 1)
res19:scala.collection.immutable.Map [String,Int] = Map(a - > 1)
解决方案其实,其原因是Predef: http://www.scala-lang.org/api/current/index.html#scala.Predef$ (它始终在Scala范围内)包含从Any到ArrowAssoc的隐式转换(方法
implicit def any2ArrowAssoc [A](x:A):ArrowAssoc [A]
)
ArrowAssoc包含方法 - >将其转换为元组。
所以基本上你在做
any2ArrowAssoc(a).->(1)
返回(a,1)。
从repl:
any2ArrowAssoc(a).->(1)
res1:(java。 lang.String,Int)=(a,1)
此外,您可以使用不可变的hashmaps这个:
val x = HashMap [Int,String](1 - >One)
x:scala.collection.immutable.HashMap [Int,String] = Map((1,One))
val y = x ++ HashMap [Int,String]( 2 - > Two)
y:scala.collection.immutable.Map [Int,String] = Map((1,One),(2,Two))
val z = x +(3 - > Three)
z:scala.collection.immutable.HashMap [Int,String] = Map((1,One),(3,Three))
Scala REPL gives the same type for both expressions - (tuple? -- strange!). Yet
("a" ->1)
which is a Map I can add to map and("a", 1)
can not. Why Scala REPL shows tuple type type for Map expression?scala> :t ("a" -> 1) (String, Int) scala> :t ("a",1) (String, Int) scala> val m = Map.empty[String, Int] m: scala.collection.immutable.Map[String,Int] = Map() scala> m + ("a",1) <console>:9: error: type mismatch; found : String("a") required: (String, ?) m + ("a",1) ^ scala> m + ("a" ->1) res19: scala.collection.immutable.Map[String,Int] = Map(a -> 1)
解决方案Actually, the reason for this is that Predef: http://www.scala-lang.org/api/current/index.html#scala.Predef$ (which is always in scope in Scala) contains an implicit conversion from Any to ArrowAssoc (the method
implicit def any2ArrowAssoc[A](x: A): ArrowAssoc[A]
)ArrowAssoc contains the method -> which converts it to a tuple.
So basically you are doing
any2ArrowAssoc("a").->(1)
which returns ("a",1).From repl:
any2ArrowAssoc("a").->(1) res1: (java.lang.String, Int) = (a,1)
Furthermore, you can work on immutable hashmaps like this:
val x = HashMap[Int,String](1 -> "One") x: scala.collection.immutable.HashMap[Int,String] = Map((1,One)) val y = x ++ HashMap[Int,String](2 -> "Two") y: scala.collection.immutable.Map[Int,String] = Map((1,One), (2,Two)) val z = x + (3 -> "Three") z: scala.collection.immutable.HashMap[Int,String] = Map((1,One), (3,Three))
这篇关于为什么Scala REPL显示Map表达式的元组类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!