Home > Software engineering >  Triggering some method when a value in a trait is set
Triggering some method when a value in a trait is set

Time:11-11

There's the following trait:

Trait Example{

    val foo : String
}

Then from another class that uses Example I set foo = "bar". Is there an easy way to for example do print(foo) or execute some other function when this value is set? Without having to touch the assignation preferably, just code within the trait class.

The options I tried would require making foo a function and then it would be called differently, so I'm not sure what's the best way to proceed.

CodePudding user response:

So, from the fact that your foo is abstract and immutable, I am going to assume that by "uses Example" you mean a subclass, and by "I set foo = "bar", you mean setting the value of a variable in constructor, not trying to mutate it on an instance (which wouldn't work since it's a val`).

Something like this, right?

class Foo extends Example { 
  val foo = "foo"
}

And now you seem to want to intercept that "assignment" and print out the value.

First of all, note, that since it is immutable (aka, a "constant"), it can only be assigned once, during construction of an instance. So, you can write something like:

class Foo extends Example { 
   print("Assigning foo to foo") 
   val foo = "foo"
}

Or if you want the value to be dynamic, you can do this:

class Bar(x: String) extends Example { 
    println(s"Assigning $x to foo") 
    val foo = "foo"
}

or just this:

case class Baz(foo: String) extends Example { 
   println(s"Assigned $foo to foo")
}

CodePudding user response:

Okay found a direct way to do it (even though it did make me change all the assignations):

lazy val foo : String = ""
print(foo)

and then in every assignement override lazy val foo = "bar", then it will print directly after the value is set.

However I'm not sure if this is a "proper" way to do this.

  • Related