为什么此Scala代码的编译错误类型不匹配 [英] Why this scala code has a compilation error type mismatch

查看:61
本文介绍了为什么此Scala代码的编译错误类型不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么使用此scala代码

Why this scala code

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

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

=:= 不对称.

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

另请参见 cats.evidence.Is scalaz.Leibniz .

在scala 2.13中,您也可以这样做

In scala 2.13 you can also do

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

这篇关于为什么此Scala代码的编译错误类型不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆