这更像是一个设计问题...
我真的很喜欢 Scala 的案例类并且经常使用它们。但是,我发现我经常将我的参数包含在Options
(或者更确切地说,Lift's Boxes
)中并设置默认值以允许灵活性并考虑到用户可能并不总是指定所有参数。我想我采用了这种做法。
我的问题是,这是一个合理的方法吗?鉴于一切都可能是可选的,可能会有很多样板和检查,以至于我想知道我是否不只是使用我的案例类,Map[String, Any]
并且想知道我是否会更好地使用Map
.
让我给你一个真实的例子。在这里,我正在模拟汇款:
case class Amount(amount: Double, currency: Box[Currency] = Empty)
trait TransactionSide
case class From(amount: Box[Amount] = Empty, currency: Box[Currency] = Empty, country: Box[Country] = Empty) extends TransactionSide
case class To(amount: Box[Amount] = Empty, currency: Box[Currency] = Empty, country: Box[Country] = Empty) extends TransactionSide
case class Transaction(from: From, to: To)
我认为比较容易理解。在这个最简单的情况下,我们可以Transaction
这样声明:
val t = Transaction(From(amount=Full(Amount(100.0)), To(country=Full(US)))
我已经可以想象你认为它很冗长。如果我们指定所有内容:
val t2 = Transaction(From(Full(Amount(100.0, Full(EUR))), Full(EUR), Full(Netherlands)), To(Full(Amount(150.0, Full(USD))), Full(USD), Full(US)))
另一方面,尽管不得不Full
到处乱扔,你仍然可以做一些很好的模式匹配:
t2 match {
case Transaction(From(Full(Amount(amount_from, Full(currency_from1))), Full(currency_from2), Full(country_from)), To(Full(Amount(amount_to, Full(currency_to1))), Full(currency_to2), Full(country_to))) if country_from == country_to => Failure("You're trying to transfer to the same country!")
case Transaction(From(Full(Amount(amount_from, Full(currency_from1))), Full(currency_from2), Full(US)), To(Full(Amount(amount_to, Full(currency_to1))), Full(currency_to2), Full(North_Korea))) => Failure("Transfers from the US to North Korea are not allowed!")
case Transaction(From(Full(Amount(amount_from, Full(currency_from1))), Full(currency_from2), Full(country_from)), To(Full(Amount(amount_to, Full(currency_to1))), Full(currency_to2), Full(country_to))) => Full([something])
case _ => Empty
}
这是一个合理的方法吗?使用 a 会更好地为我服务Map
吗?或者我应该以不同的方式使用案例类吗?也许使用案例类的整个层次结构来表示具有不同指定信息量的交易?