Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting multiple object attributes in Scala?

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?)

like image 656
GroomedGorilla Avatar asked Feb 12 '23 02:02

GroomedGorilla


2 Answers

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)
like image 147
Michael Zajac Avatar answered Feb 13 '23 15:02

Michael Zajac


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
     | }
like image 39
Daniel C. Sobral Avatar answered Feb 13 '23 16:02

Daniel C. Sobral