Scala trait implementation

試著忘記壹切 提交于 2020-01-06 06:46:37

问题


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)


来源:https://stackoverflow.com/questions/47137581/scala-trait-implementation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!