【发布时间】:2014-10-07 14:05:33
【问题描述】:
有人可以解释为什么以下内容不起作用。当我做toSet 时,不知何故失去了编译类型推断的一些信息,但我不明白为什么。
scala> case class Foo(id: Int, name: String)
defined class Foo
scala> val ids = List(1,2,3)
ids: List[Int] = List(1, 2, 3)
scala> ids.toSet.map(Foo(_, "bar"))
<console>:11: error: missing parameter type for expanded function ((x$1) => Foo(x$1, "bar"))
ids.toSet.map(Foo(_, "bar"))
^
scala> ids.map(Foo(_, "bar")).toSet
res1: scala.collection.immutable.Set[Foo] = Set(Foo(1,bar), Foo(2,bar), Foo(3,bar))
【问题讨论】:
-
似乎编译器需要一些帮助来明确类型,
ids.toSet.map(Foo(_: Int, "bar")) -
是的,但是为什么当我在地图之后执行 toSet 时编译器不需要这些信息??
-
令人困惑的是,这行得通,
val a = ids.toSet ; a.map(Foo(_, "bar")) -
在这里考虑一个类似的错误:stackoverflow.com/q/4701761/3189923
-
@enzyme:尽管表面上很相似,但这并不是真正的类似错误。在 OP 的情况下,错误与
toSet的使用有关。请注意,将toSet替换为toSeq时,它编译得很好。
标签: scala