Type mismatch when using higher-kinded types

137 views Asked by At

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?

1

There are 1 answers

1
Eugene Zhulenev On BEST ANSWER

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.