Gad
Gad

Reputation: 42306

call constructor with missing arguments

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?

Upvotes: 2

Views: 550

Answers (1)

drexin
drexin

Reputation: 24413

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

Upvotes: 6

Related Questions