0

I have a case class:

case class EvaluateAddress(addressFormat: String,
                             screeningAddressType: String,
                             value: Option[String]) {
}

This was working fine until I have a new use case where "value" parameter can be a class Object instead of String.

My initial implementation to handle this use case:

case class EvaluateAddress(addressFormat: String,
                             screeningAddressType: String,
                             addressId: Option[String],
                             addressValue: Option[MailingAddress]) {

  @JsonProperty("value")
  def setAddressId(addressId: String): Unit = {
    val this.`addressId` = Option(addressId)
  }

  def this(addressFormat: String, screeningAddressType: String, addressId: String) = {
    this(addressFormat, screeningAddressType, Option(addressId), None)
  }

  def this(addressFormat: String, screeningAddressType: String, address: MailingAddress) = {
    this(addressFormat, screeningAddressType, None, Option(address))
  }
}

but I don't feel this is a good approach and it might create some problem in future.

What are the different ways I can accomplish the same?

Edit: Is there a way I can create a class containing three parameters: ** addressFormat, screeningAddressType, value** and handle both the use cases?

0

2 Answers 2

4

You do not need to provide auxilliary constructors here and neither the setter. You could simply use the copy method provided by the case class.

For example:

case class MailingAddress(email:String)
case class EvaluateAddress(addressFormat: String,
                             screeningAddressType: String,
                             addressId: Option[String],
                             addressValue: Option[MailingAddress])

scala> val y = EvaluateAddress("abc", "abc", None, None)
y: EvaluateAddress = EvaluateAddress(abc,abc,None,None)

scala> y.copy(addressId = Some("addressId"))
res0: EvaluateAddress = EvaluateAddress(abc,abc,Some(addressId),None)
Sign up to request clarification or add additional context in comments.

Comments

3

You can have a default value for fields in a case class.

So you can have the Optional fields default to None :

case class EvaluateAddress(addressFormat: String,
                             screeningAddressType: String,
                             addressId: Option[String] = None,
                             addressValue: Option[MailingAddress] = None)

Then when you create a new instance of EvaluateAddress, you can choose to pass a value for either of addressId, or addressValue or both ..or nothing at all.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.