【问题标题】:Why view bound and context bound fails to detect implicits present in the context为什么视图绑定和上下文绑定无法检测到上下文中存在的隐含
【发布时间】:2021-10-16 15:49:09
【问题描述】:

我是 scala 的新手,我正在尝试实现一个附加两个数字或字符串的方法方法“append”。

在此代码上实践的想法来自this 帖子,我指的是append 方法和Appendable trait 用于创建implicits 的示例。

我尝试使用视图绑定和上下文绑定概念在我的 IntelliJ 中复制相同的代码,但不知何故它不起作用。

任何人都可以请提出以下代码中缺少的内容吗?为什么它失败了? 我还尝试复制相同的here

trait Appendable[A]{
  def append(a: A, b : A) : A
}

object Appendable {
  implicit val appendableString = new Appendable[String] {
    override def append(a: String, b : String): String = a + b
  }

  implicit val appendableInt = new Appendable[Int] {
    override def append(a: Int, b : Int): Int = a + b
  }
}

object ItemAppenderTester extends Object {
  def appendItem[A <% Appendable[A]]( a : A, b : A) = a append b
  def appendItem2[A : Appendable[A]]( a : A, b : A) = implicitly[Appendable[A]].append(a,b)

  def appendItem3(a : A, b : A) (implicit  ev : Appendable[A]) = ev.append(a,b)
  appendItem(1,2)
}

【问题讨论】:

    标签: scala implicit context-bound view-bound


    【解决方案1】:
    def appendItem[A <% Appendable[A]]( a : A, b : A)
    

    现在是错误的。 X &lt;% Y 表示 (implicit ev: X =&gt; Y)。您没有定义隐式 A =&gt; Appendable[A](与 Medium 上的文章相反,请参阅那里的 toAppendable)。 &lt;% 也已弃用。

    appendItem2 可以修复:

    def appendItem2[A : Appendable]( a : A, b : A)
    

    appendItem3 可以修复:

    def appendItem3[A](a : A, b : A) (implicit  ev : Appendable[A])
    

    实际上appendItem2被脱糖成appendItem3

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-02
      • 2011-02-28
      • 2015-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多