2

首先,这个:

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

我检查并额外的括号不能解决问题。

4

2 回答 2

1

使用 toSet 时类型推断的原因,因此您需要为链调用或拆分调用提供类型提示。你可以在这里找到详细信息https://issues.scala-lang.org/browse/SI-7743https://issues.scala-lang.org/browse/SI-9091

于 2016-12-05T13:31:12.950 回答
0

代码应该是:

"1 2".split(" ").toSet map (x: String => x.toInt)

在这里,我明确指定 Set 包含字符串。

链式调用在 Scala 中存在此问题,编译器希望您提供参数的类型。

于 2016-12-05T14:47:19.230 回答