【问题标题】:Why this scala code has a compilation error type mismatch为什么这个 scala 代码有编译错误类型不匹配
【发布时间】:2020-11-01 01:57:48
【问题描述】:

为什么是这个 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)

【问题讨论】:

    标签: scala implicit type-systems


    【解决方案1】:

    问题是你需要证据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)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-18
      • 2021-01-14
      • 2016-06-04
      • 1970-01-01
      • 2015-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多