我正在尝试在Miles Sabin的博客文章中定义的Scala的联合类型:
http://www.chuusai.com/2011/06/09/scala-union-types-curry-howard/
并在中讨论过
对于那里定义的简单情况,它们工作正常,但我要做的是使用它们在Play Framework中创建一个只接受某些值(String,Boolean,Int,Undefined)的通用JSON解析器,然后成功传递它们.
这是我的代码:
type UpdateType = Option[String] |?| Option[Int] |?| Option[Boolean] |?| Option[List[Int]]
def withValue[T : (UpdateType)#?](request: Request[JsValue])(block: (String, T) => Future[SimpleResult]) = {
val field = request.body \ ("field")
val value = request.body \ ("value")
(field, value) match {
case (x: JsString, y: JsString) => block(x.value.toString, Some(y.value.toString))
case (x: JsString, y: JsNumber) => block(x.value.toString, Some(y.value.intValue))
case (x: JsString, y: JsBoolean) => block(x.value.toString, Some(y.value.booleanValue))
case (x: JsString, y: JsUndefined) => block(x.value.toString, None)
case _ => …Run Code Online (Sandbox Code Playgroud)