![](/img/trans.png)
[英]scala Play Anorm parser throws UnexpectedNullableFound in model
[英]Object construction with validation in Scala, using that in an Anorm parser
我有一个简单的案例类金额如下
case class Amount(value: Long, currency: Currency)
还有一个附带的对象,用于将字符串货币代码转换为Currency对象
object Amount {
private val log = Logger(getClass)
def apply(value: Long, currencyCode: String) : Amount = {
try {
Amount(value, Currency.getInstance(currencyCode))
} catch {
case e: Exception =>
log.error(s"Invalid currency code [$currencyCode]")
throw new Exception(s"Invalid currency code [$currencyCode]")
}
}
}
调用方式:
val amount : Amount = Amount(1234, "USD")
当我从数据库中读取一些数据时,我有一个自定义解析器,例如
implicit val amountParser = Macro.parser[Amount]("value", "currencyCode")
但是,编译器抱怨
scala.ScalaReflectionException: value apply encapsulates multiple overloaded alternatives and cannot be treated as a method. Consider invoking `<offending symbol>.asTerm.alternatives` and manually picking the required method
[error] at scala.reflect.api.Symbols$SymbolApi$class.asMethod(Symbols.scala:228)
[error] at scala.reflect.internal.Symbols$SymbolContextApiImpl.asMethod(Symbols.scala:84)
[error] at anorm.Macro$.parserImpl(Macro.scala:70)
[error] at anorm.Macro$.namedParserImpl_(Macro.scala:25)
[error] implicit val amountParser = Macro.parser[Amount]("value", "currencyCode")
我该如何工作?
UPDATE
了解了@MikeAllen的响应后,我决定保留case class Amount
和object Amount
不变,而是为Amount编写了一个自定义解析器,如下所示
implicit private val amountParser = for {
value <- long("value")
currencyCode <- str("currency_code")
} yield {
Amount(value, currencyCode)
}
Scala编译器将自动生成一个Amount.apply
工厂方法来创建case class
实例,这就是为什么会出现此错误的原因-因为您有多个Amount.apply
方法。 其中一个采用类型( Long
, Currency
)的参数,另一个采用类型( Long
, String
)的参数。 错误消息表明,您需要从通过反射报告的重载替代项中选择一种。
或者,您的案例类和同伴可以按以下方式重做:
final case class Amount(value: Long, currencyCode: String) {
/** Currency. Will create an exception on instantiation if code is invalid. */
val currency: Currency = {
try {
Currency.getInstance(currencyCode)
}
catch {
case e: Exception =>
Amount.log.error(s"Invalid currency code [$currencyCode]")
throw new Exception(s"Invalid currency code [$currencyCode]")
}
}
}
object Amount {
private val log = Logger(getClass)
}
诚然,这并不那么优雅,因为您现在有了一个字段currency
,它不是case类的参数之一,并且不能用于模式匹配,同时还带有字符串形式。
更好的解决方案是保留原始case class
并将货币代码字段从String
转换为Currency
,然后再创建Amount
实例,作为解析器的一部分:
val amountMapping = {
get[Long]("value") ~ get[String]("currencyCode") map {
case value ~ currencyCode => {
val currency = {
try {
Currency.getInstance(currencyCode)
}
catch {
case e: Exception =>
Amount.log.error(s"Invalid currency code [$currencyCode]")
throw new Exception(s"Invalid currency code [$currencyCode]")
}
}
Amount(value, currency)
}
}
}
然后,您可以使用它来分析行,例如:
def amounts(): List[Amount] = SQL("select * from amounts").as(amountMapping *)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.