Why this scala code has a compilation error type mismatch
Asked Answered
T

1

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)
Tussock answered 11/7, 2020 at 12:44 Comment(0)
K
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)
}
Krugersdorp answered 11/7, 2020 at 13:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.