使用较高级别的类型时类型不匹配

时间:2014-11-24 00:23:31

标签: scala types compiler-errors higher-kinded-types

在库中,有一个类型较高的类采用一个类型参数。我想给它一个带两个类型参数的类型,所以我使用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

为什么会出现类型错误?

1 个答案:

答案 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在这种情况下不起作用。

相关问题