为什么这个scala代码有编译错误类型不匹配

Why this scala code has a compilation error type mismatch

为什么这个 scala 代码

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

触发此编译错误

[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)

问题是你需要证据 String =:= T 而不是 T =:= String

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

=:=不对称。

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

另请参阅 cats.evidence.Isscalaz.Leibniz

在 scala 2.13 中你也可以这样做

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