Search code examples
scalaimplicittype-systems

Why this scala code has a compilation error type mismatch


Why this scala code

case class Foo[T]() {
  def bar(tt: T): Unit = ???
  def bar_(s: String)(implicit ev : T =:= String): Unit = bar(s)
}

triggers this compilation error

[error] type mismatch;
[error]  found   : s.type (with underlying type String)
[error]  required: T
[error]     def foo2(s: String)(implicit ev: T =:= String) = foo(s)

Solution

  • The thing is that you need evidence String =:= T rather than T =:= String.

    case class Foo[T]() {
      def bar(tt: T): Unit = ???
      def bar_(s: String)(implicit ev : String =:= T): Unit = bar(s)
    }
    

    =:= is not symmetric.

    https://typelevel.org/blog/2014/07/02/type_equality_to_leibniz.html

    See also cats.evidence.Is, scalaz.Leibniz.

    In scala 2.13 you can also do

    def bar_(s: String)(implicit ev : T =:= String): Unit = {
      implicit val ev1 = ev.flip
      bar(s)
    }