I'm not too sure what the correct name for this would be, but is there a way of setting/changing more than one of an object's attributes at once in Scala? (where the object has already been initialised)
I'm looking for something of the sort:
sampleObject.{
name = "bob",
quantity = 5
}
as opposed to:
sampleObject.name = "bob"
sampleObject.quantity = 5
Does Scala have any such functionality? (and what is the correct term for it?)
There is no such syntax that I'm aware of, and a good reason I think. In Scala, using mutable properties like this is highly discouraged. A feature that is like this exists for case classes, but in an immutable fashion. All case classes come with a copy
method that allows you to make a copy of the class instance, while changing only the fields you specify.
case class Sample(name: String, quantity: Int, other: String)
scala> val sample = Sample("Joe", 2, "something")
sample: Sample = Sample(Joe,2,something)
scala> val sampleCopy = sample.copy(
name = "bob",
quantity = 5
)
sampleCopy: Sample = Sample(bob,5,something)
There is such a thing, in a way. Honestly, using a case class copy
method is preferable, imho, as described in other answers. But Scala has a way to bring an object's members into scope, such as shown in this REPL session:
scala> object sampleObject {
| var name = "fred"
| var quantity = 1
| }
defined object sampleObject
scala> { import sampleObject._
| name = "bob"
| quantity = 5
| }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With