具有参数化类型的类的flatMap不会编译

时间:2014-11-19 13:42:17

标签: scala

有人可以告诉我为什么会这样:

case class Item[A, B, C](a : A, b: B, c: C)
val s1 = Seq(1, 2, 3)
val s2: Seq[Item[_,_,_]] = Seq(Item(3, "q", "r"), Item(4, "s", "t"), Item(5, "u", "v"))
s1.flatMap { i =>
  s2.find(_.a == i) match {
    case Some(i2) => Some(Item(i2.a, i2.c, i2.b))
    case None => None
  }
}

给我以下编译器错误以及解决它的最佳方法:

- no type parameters for method flatMap: (f: Int => scala.collection.GenTraversableOnce[B])(implicit bf: 
     scala.collection.generic.CanBuildFrom[Seq[Int],B,That])That exist so that it can be applied to arguments (Int => Iterable[Item[_0]] forSome { type _0 }) --- 
     because --- argument expression's type is not compatible with formal parameter type; found : Int => Iterable[Item[_0]] forSome { type _0 } required: Int 
     => scala.collection.GenTraversableOnce[?B]
- Cannot construct a collection of type That with elements of type B based on a collection of type Seq[Int].
- Cannot construct a collection of type That with elements of type B based on a collection of type Seq[Int].

1 个答案:

答案 0 :(得分:0)

使项目协变确实使它编译:

case class Item[+A, +B, +C](a : A, b: B, c: C)
...