首页 文章

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

提问于
浏览
3

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

  • 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在这种情况下不起作用 .

相关问题