在库中,有一个类型较高的类采用一个类型参数。我想给它一个带两个类型参数的类型,所以我使用type
表达式来修复另一个参数。
但它并没有像我期望的那样结束。
代码简化为:
object Main {
class Bar[T[_]] {
def bar[A]: Option[T[A]] = None
}
def foo[A] = {
type T[B] = Map[A, B]
new Bar[T]
}
val f: Option[Map[String, Int]] = foo[String].bar[Int]
}
编译时遇到错误(Scala 2.11.4):
test.scala:12: error: type mismatch;
found : Option[T[Int]]
(which expands to) Option[scala.collection.immutable.Map[A,Int]]
required: Option[Map[String,Int]]
val f: Option[Map[String, Int]] = foo[String].bar[Int]
^
one error found
为什么会出现类型错误?
答案 0 :(得分:5)
类型labmdas应该有所帮助:
class Bar[T[_]] {
def bar[A]: Option[T[A]] = None
}
def foo[A] = {
new Bar[({type M[B] = Map[A, B]})#M]
}
val f: Option[Map[String, Int]] = foo[String].bar[Int]
但是我不能回答为什么T在这种情况下不起作用。