2

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)
Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
Yann Moisan
  • 8,161
  • 8
  • 47
  • 91

1 Answers1

5

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)
}
Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66