Scala 对 Int 的隐式转换

Scala implicit conversion on Ints

假设我有以下方法:

  def main(args: Array[String]): Unit = {
    println(Ring(2) + Ring(3) + Ring(-1) + Ring(10))
  }

产生:

( [2] left-> ( [-1] left-> null, right-> null), right-> ( [3] left-> null, right-> ( [10] left-> null, right-> null)))

我想编写一个隐式转换,它允许我按以下方式编写代码:

 def main(args: Array[String]): Unit = {
    val r :Ring = 2 + 3 + (-1) + 10
    println(r)
  }

但遵循隐式方法

  implicit def intToRing(x :Int): Ring = {
    new Ring(x)
  }

以这种方式工作,首先它总结所有元素,然后创建 Ring what produces:

( [14] left-> null, right-> null)

是否可以实现 'not greedy' 隐式转换来满足我的要求?

您应该能够通过显式转换第一个 Int 来做到这一点:

val r = (2: Ring) + 3 + (-1) + 10

这会强制编译器寻找一种将“3”加到 Ring 的方法,这应该会强制进行隐式转换,否则它可以愉快地使用整数加法而无需寻找隐式转换.

我能想到的唯一其他方法是为 Ring 提供替代方法名称(直接或通过隐式包装器 class 等),例如:

def +^(other: Ring): Ring = this + other

并使用该运算符:

val r = 2 +^ 3 +^ (-1) +^ 10