例如,我在+*
的以下包装类中为加权和定义了一个Double
运算符:
class DoubleOps(val double: Double) {
def +*(other: DoubleOps, weight: Double): DoubleOps =
new DoubleOps(this.double + other.double * weight)
}
object DoubleOps {
implicit def DoubleToDoubleOps(double: Double) = new DoubleOps(double)
}
根据这个定义,我可以进行以下计算:
var db: DoubleOps = 1.5
import DoubleOps._
db = db +* (2.0, 0.5)
println(db)
我是否有办法使用赋值运算符计算db
来获取结果,比如定义+*=
,以便我可以使用:
db +*= (2.0, 0.5)
这可能吗?
答案 0 :(得分:4)
import scala.languageFeature.implicitConversions
class DoubleOps(var double: Double) {
def +*(other: DoubleOps, weight: Double): DoubleOps =
new DoubleOps(this.double + other.double * weight)
def +*=(other: DoubleOps, weight: Double): Unit = {
this.double = this.double + other.double * weight
}
}
object DoubleOps {
implicit def DoubleToDoubleOps(double: Double) = new DoubleOps(double)
}
val d: DoubleOps = 1.5
d +*= (2.0, 0.5)