GroomedGorilla
GroomedGorilla

Reputation: 1002

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

Upvotes: 4

Views: 2623

Answers (2)

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297285

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
     | }

Upvotes: 1

Michael Zajac
Michael Zajac

Reputation: 55569

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)

Upvotes: 7

Related Questions