【问题标题】:Type mismatch when using higher-kinded types使用更高种类的类型时类型不匹配
【发布时间】:2014-11-24 09:25:32
【问题描述】:

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

为什么会出现类型错误?

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 既然你提到了,我以前见过那些用的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多