I think this will be better explained with an example
I have the following case class
case class Person(name: String = "no name", surname: String = "no surname")
And I want to make a general function to populate it from, for example, a json message, that might not specify all fields
I know that to use the default values the simple answer is not to pass them to the constructor, but if I have several fields that may or may not appear in the json, I should have to use a huge switch sentence covering every possible combination of missing parameters. In this case, after reading the json, I should take care of name & surname present, no name, no surname and no name nor surname case... (Gee, I hope I made myself clear).
To be more precise, I'm trying to develop a function that allows me to create a person from the following json values, using the default values when there's some parameter missing
{ "name": "john", "surname": "doe" }
{ "surname": "doe" }
{ "name": "john" }
{ }
That's why I'm looking for a more general way to handle this.
(I'll show some pseudo code to give and idea of what I'm trying to achieve)
I was thinking about something like:
val p = Person(name= "new person name", surname= Unit)
And in that case surname should get the default value
Or something like
val p = Person( Map( "name" -> "new person name" ) _* )
So that it also takes the default value for surname
Or maybe doing it in the constructor, if I detect a null value (or None) I could assign the default value.
In fact, I'm trying to avoid repeating the definition of the default values.
Anyway, what would be the most idiomatic way to achieve such a thing?