Search code examples
scaladefault-valuecase-class

How can I check that all object's fields with default value were set?


Most of time default values are very suitable, but in some cases I want to check that they were set manually.

Example

//most fields with default value
case class Person(
  name: Option[String] = None,
  name2: Option[String] = None,
  bithYear: Option[Int] = None      
)


object OtherPersonToPersonConverter {
  def convert(other: OtherPerson): Person = {
    Person(
      name = other.name,
      name2 = other.name2,
      bithYear = other.bithYear 
    )
  }

Then I added another field with default value

case class Person(
  name: Option[String] = None,
  name2: Option[String] = None,
  bithYear: Option[Int] = None,
  city: Option[String] = None
)

I should fix the converter, but I don't know about this because of default value usage. Is there any way to create an object without usage of default values (and produce compilation time error)?


Solution

  • How about just:

    case class Person(
      name: Option[String] = None,
      name2: Option[String] = None,
      bithYear: Option[Int] = None,
      city: Option[String]
    )