如何覆盖 Scala 中的预定义函数?

How to override predefined function in Scala?

我需要实现功能to。我有以下工作代码:

object Main {

  val m = 0
  val km = 1

  implicit def wrapM(v: Int) = new {
    def m = v
  }

  implicit def wrapKm(v: Int) = new {
    def km = v * 1000
  }

  implicit class toWrap(fromVal: Int) {
    def too (value: Int): Double = {
      if (value.equals(km)) {
        fromVal / 1000.0
      } else {
        0
      }
    }
  }

  def main(args:Array[String])
  {
    println(53.m too km)
  }
}

但是有一个问题。我使用 too 名称,而不是 to。如果我将其重命名为 to,则会出现错误:

Error:(30, 16) type mismatch;
 found   : Int
 required: ?{def to(x: ? >: Int): ?}
Note that implicit conversions are not applicable because they are ambiguous:
 both method intWrapper in class LowPriorityImplicits of type (x: Int)scala.runtime.RichInt
 and method toWrap in object Main of type (fromVal: Int)Main.toWrap
 are possible conversion functions from Int to ?{def to(x: ? >: Int): ?}
    println(53.m to km)
               ^

这是因为还有一个函数to - scala.runtime.RichInt#to.

Scala 不允许在一个上下文中定义两个具有相同参数集的隐式....

但是有办法。您应该在 toWrap implicit 中使用不同的类型,而不是标准的 Scala Int.

检查下面的示例。 我的想法是为一些包装器 class IntWrap 而不是标准 Int

实现方法 to
 case class IntWrap(v: Int)  {

  }

  val m = 0
  val km = 1

  implicit def wrapM(v: Int) = new {
    def m = IntWrap(v)
  }

  implicit def wrapKm(v: Int) = new {
    def km = v * 1000
  }

  implicit class toWrap(fromVal: IntWrap) {
    def to(value: Int): Double = {
      if (value.equals(km)) {
        fromVal.v / 1000.0
      } else {
        0
      }
    }
  }

  def main(args:Array[String])
  {

    println(53.m to km)
  }