Scala下划线奇怪的行为:错误:缺少扩展功能的参数类型



首先,此:

"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)

在这里,我明确指定该集合包含字符串。

链条呼叫在Scala中有此问题,其中编译器期望您提供参数的类型。

最新更新