这个问题在这里已有答案:
首先,这个:
"1 2".split(" ").toSet
还有这个:
Set("1", "2")
两者都评价同样的东西,即
res1: scala.collection.immutable.Set[String] = Set(1, 2)
为什么然后,当我这样做时:
Set("1", "2") map (_.toInt)
我得到了预期的结果:
res2: scala.collection.immutable.Set[Int] = Set(1, 2)
但是当我这样做时:
"1 2".split(" ").toSet map (_.toInt)
我有:
<console>:12: error: missing parameter type for expanded function ((x$1) => x$1.toInt)
"1 2".split(" ").toSet map (_.toInt)
我查了一下,额外的括号没有解决问题。
使用toSet时在类型推断中的原因,因此您需要为链调用提供类型提示或拆分调用。你可以在这里找到详细信息https://issues.scala-lang.org/browse/SI-7743,https://issues.scala-lang.org/browse/SI-9091
代码应该是:
"1 2".split(" ").toSet map (x: String => x.toInt)
在这里,我明确指定Set包含字符串。
链调用在Scala中存在此问题,编译器希望您提供参数的类型。