CyberPlayerOne
CyberPlayerOne

Reputation: 3170

How to define an assignment operator in Scala?

For example, I have defined a +* operator for weighted sum in the following wrapper class for 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)
  }

With this definition, I can have the following calculation:

var db: DoubleOps = 1.5
import DoubleOps._
db = db +* (2.0, 0.5)
println(db)

Is there a way I can calculate db using an assignment operator to get the result, like to define a +*=, so that I can use:

db +*= (2.0, 0.5)

Is this possible?

Upvotes: 3

Views: 201

Answers (1)

sarveshseri
sarveshseri

Reputation: 13985

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)

Upvotes: 4

Related Questions