gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 19:22:37 26 4
gpt4 key购买 nike

为什么使用这个 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)
}

关于scala - 为什么这个scala代码有编译错误类型不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62849306/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com