user2737635
user2737635

Reputation:

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

Upvotes: 0

Views: 575

Answers (2)

Dan Getz
Dan Getz

Reputation: 9152

You can create as many constructor functions as you'd like. A good place to put them is in the companion object:

object Person {
  def create(name: Option[String], name2: Option[String], ...): Person = Person(
    name = name,
    name2 = name2,
    ...
  )
}

The constructor function Person(...) is equivalent to Person.apply(...), that is, calling the apply() method of the companion object, so you're just making another one by defining Person.create() (or whatever you want to name it). By creating multiple constructor functions, one with default values and one without, you can control whether or not the default values are used when you create your Person instance by choosing which method you call.

If it works better for you, you could make create() be the one with default arguments, and not define default arguments for apply() (that is, in the case class definition).

Upvotes: 0

Jatin
Jatin

Reputation: 31744

How about just:

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

Upvotes: 1

Related Questions