3

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?

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

5 Comments

We all should take this as an opportunity to meditate on the distinction between reassignment and mutation.
Yes that is one subtlety. The OP wants mutation but he wrote assignment.
Right, reassignment cannot be a method AFAIK because it doesn't change something within the object, it changes something in the environment.
It's because in the book "Scala for the impatient" the author calls it "assignment operator".
@Tyler提督九门步军巡捕五营统领 I see. I think I remember that part of the book.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.