Scala: how to initialize an object using default values

If you want the default value to be used, you normally just leave off that named argument:

scala> val p = Person(name = "new person name")
p: Person = Person(new person name,no surname)

But, since you want to explicitly know whether a value should be defaulted or not, you could implement your Map-based idea in a constructor. If you don't want to repeat the defaults, how about these two options:

Option 1: Externalized constants for defaults

Set the defaults externally. Use them in both the main constructor and the Map-based constructor.

val nameDefault = "no name"
val surnameDefault = "no surname"

case class Person(name: String = nameDefault, surname: String = surnameDefault) {
  def this(m: Map[String, String]) =
    this(m.getOrElse("name", nameDefault), m.getOrElse("surname", surnameDefault))
}

Usage:

new Person(name = "new person name", surname = "new person surname")
new Person(Map("name" -> "new person name"))
new Person(name = "new person name")

Option 2: Optionified alternate constructor

You may find this a little cleaner since it doesn't rely on externalized constants. The only downside here is that if you want to construct with only some of the parameters, you have to wrap each one in Some().

case class Person(name: String, surname: String) {
  def this(name: Option[String] = None, surname: Option[String] = None) =
    this(name.getOrElse("no name"), surname.getOrElse("no surname"))

  def this(m: Map[String, String]) = this(m.get("name"), m.get("surname"))
}

Usage:

new Person(name = "new person name", surname = "new person surname")
new Person(Map("name" -> "new person name"))
new Person(name = Some("new person name"))
new Person(name = "new person name") // can't do this