【发布时间】:2023-03-03 04:42:01
【问题描述】:
我正在尝试写这样的东西:
trait Typed[T]
trait Test {
def testMap: Map[Typed[_], Int]
def test = testMap.flatMap {case (typed, size) => Seq.fill(size)(typed)}
}
但我收到以下错误:
error: no type parameters for method flatMap: (f: ((Typed[_], Int)) => Traversable[B])(implicit bf: scala.collection.generic.CanBuildFrom[scala.collection.immutable.Map[com.quarta.service.querybuilder.Typed[_],Int],B,That])That exist so that it can be applied to arguments (((Typed[_], Int)) => Seq[Typed[_0]] forSome { type _0 })
--- because ---
argument expression's type is not compatible with formal parameter type;
found : ((Typed[_], Int)) => Seq[Typed[_0]] forSome { type _0 }
required: ((Typed[_], Int)) => Traversable[?B]
def test = testMap.flatMap {case (typed, size) => Seq.fill(size)(typed)}
如果将 testMap 类型更改为以下代码,则此代码有效:
def testMap: Map[Typed[Any], Int]
有什么区别以及如何解决我的问题?
【问题讨论】:
-
为什么需要通配符而不是
Any?您希望如何使用此特征? -
我展示了这个特征作为例子。问题是我必须编写采用 Map[Typed[],Int] 并根据大小变量将其转换为 Seq[Typed[]] 的方法。
-
但是
Map[Typed[_],Int]会有一些类型。为什么不参数化它,Map[Typed[A],Int]而不是通配符呢? -
因为这个地图会包含不同类型的元素(Typed[T1], Typed[T2]...Typed[TN])。
标签: generics scala types scala-collections