简体   繁体   中英

Type mismatch when using higher-kinded types

In a library, there is a class with a higher-kinded type taking one type parameter. I want to give it a type that takes two type parameters, so I use a type expression to fix the other parameter.

But it doesn't turn out like I expect.

The code reduces to this:

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]

}

I get an error when compiling (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

Why is there a type error?

Type labmdas should help:

  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]

However I can't answer why type T doesn't work in this case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM