【问题标题】:Confusion about implicit example in scala [duplicate]关于scala中隐式示例的困惑[重复]
【发布时间】:2021-01-13 21:24:01
【问题描述】:
implicit def list2ordered[A](x: List[A])(implicit elem2ordered: A => Ordered[A]): Ordered[List[A]] =
  new Ordered[List[A]] {
    //replace with a more useful implementation
    def compare(that: List[A]): Int = 1
}

println(List(1,2,3) <= List(4,5))

无法理解它是如何工作的

【问题讨论】:

  • 你能扩展你不明白的地方吗?是隐式参数吗?

标签: scala implicit-conversion implicit


【解决方案1】:
List(1,2,3) <= List(4,5)

被脱糖

list2ordered(List(1, 2, 3))(Predef.intWrapper) <= List(4, 5)

list2ordered的签名

implicit def list2ordered[A](x: List[A])(implicit elem2ordered: A => Ordered[A]): Ordered[List[A]]

表示它是一个conditional implicit conversion,即你有一个隐式转换List[A] =&gt; Ordered[List[A]],前提是你有一个隐式转换A =&gt; Ordered[A]

Predef.intWrapper 正是这种隐式转换,因为它是Int =&gt; RichIntRichInt 扩展Ordered[Int] (RichInt &lt;: ScalaNumberProxy[Int] &lt;: OrderedProxy[Int] &lt;: Ordered[Int])。

can 总是可以看到reify 是如何解决隐含问题的

import scala.reflect.runtime.universe._
println(reify{List(1,2,3) <= List(4,5)}.tree)
//App.this.list2ordered(List.apply(1, 2, 3))(((x) => Predef.intWrapper(x))).$less$eq(List.apply(4, 5))

【讨论】:

    猜你喜欢
    • 2020-12-25
    • 2019-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 2017-11-08
    • 1970-01-01
    • 2017-09-07
    相关资源
    最近更新 更多