Scala 特性实现 [英] Scala trait implementation

查看:41
本文介绍了Scala 特性实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个案例类:

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

这一直很好,直到我有了一个新用例,其中value"参数可以是类对象而不是字符串.

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?

有没有办法创建一个包含三个参数的类:** addressFormat、screeningAddressType、value** 并处理这两个用例?

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

推荐答案

您不需要在这里提供辅助构造函数,也不需要提供 setter.您可以简单地使用案例类提供的复制方法.

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.

例如:

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)

这篇关于Scala 特性实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆