在scala-forms中写入Any类型的格式化程序?

时间:2017-11-07 08:18:18

标签: forms scala formatter

我想创建类似于此

的scala表单
val conditionMapping = mapping(
    "rkey" -> optional(text),
    "rflag" -> optional(of(EnumUtils.enumFormatter(InplaceNotifyFlag))),
    "rval" -> optional(of[Any])
  )(InplaceNotifyOnCondition.apply)(InplaceNotifyOnCondition.unapply)

但Any的格式化程序不可用,如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

我假设你正在使用play框架,因为你没有指明它的来源。

Play使用不变的Formatter[A]类型类为类型A找到Formatter。许多格式化程序都内置在play.api.data.format.Formats中。

为了支持Any,您必须编写Formatter类型类的新实例:

implicit val anyFormatter: Formatter[Any] = new Formatter[Any] {
  // define the bind and unbind method
}

但正如cchantep所说,这可能不是你想要做的,因为这种隐含过于笼统,并且在你不想要的情况下会接受Any

相反,我建议你的Any课程中没有InplaceNotifyOnCodnition。相反,将Any包装在特定用例的case类中,并为此编写Formatter实例:

case class InplaceNotifyOnCondition(rkey: ..., rflag: ..., rval: Option[AnyRVal)

case class AnyRVal(rval: Any) extends AnyVal

object AnyRVal {
  implicit val rvalFormatter: Formatter[AnyRVal] = new Formatter[AnyRVal] {
    // implement
  }
}