Scala trait implementation

2019-08-23 10:12发布

问题:

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?

回答1:

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.



回答2:

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)