2

I'm just barely starting at Scala and was wondering if it was possible to create a class that has immutable properties with default values and that we can initiate passing along any property value in the constructor:

So for example in JavaScript the following is possible (end result won't be immutable but you'll get the idea):

var myObj = function(params){
    this.a = params.a || 'default a';
    this.b = params.b || 'default b';
    this.c = params.c || 'default c';
};

new myObj({c:'override c', b:'override b'});

and I would get my new object constructed with the default values and the new b and c properties... As you can see the constructor here accepts any number of object properties in any order.

So taking a very simple example in Scala:

case class Customer(
    val id: Long = 0,
    val name: String = ""
)

I know I can do this:

val customer = Customer(0, "company")

but I would like to do this:

val customer = Customer{ name = "company" }

so I don't end up with 50 constructors.

Is it possible? How?

1 Answer 1

6

You don't need to pass a hash, like in javascript, but simply assign the values to the parameters in the constructor. This is called "named parameters" and looks like this: Customer(name = "Peter")

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.