4

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

2 Answers 2

7

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

2 Comments

It seems that such a thing can be achieved via scala macros, as seen in this blog post by @TravisBrown As noted by the title, you should probably avoid it.
This seems to be what I'm after! Makes sense now, coming to think about it. I've given it a go and all seems to be working fine. Cheers
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.