如何在Scala中重写预定义函数?
我需要实现函数如何在Scala中重写预定义函数?,scala,implicit-conversion,implicit,overriding,Scala,Implicit Conversion,Implicit,Overriding,我需要实现函数到。我有以下工作代码: 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): Dou
到
。我有以下工作代码:
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)
}
}
但有一个问题。我也使用名称,而不是to
。如果将其重命名为为,则会出现以下错误:
Error:(30, 16) type mismatch;
found : Int
required: ?{def to(x$1: ? >: 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$1: ? >: Int): ?}
println(53.m to km)
^
这是因为,还有一个函数to
-scala.runtime.RichInt#to
scala不允许在一个上下文中使用相同的参数定义两个隐式
但是有一种方法。您应该在toWrap
implicit中使用不同的类型,而不是标准的scalaInt
检查下面的样本。
我的想法是为一些包装类IntWrap
实现方法to
,而不是标准的Int
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)
}
scala不允许在一个上下文中定义具有相同参数集的两个隐式。@V先生,是的,我知道。但也许有一种方法可以将隐藏到函数中?