2016-12-15 35 views
-1

空的情况下,我有以下POST体的例子:处理中阶游戏框架

{ "Id": "123abxy"} 

{ "customUrl": "http://www.whiskey.com","Id": "123abxy"} 

{ "size": "88", "customUrl": "http://www.whiskey.com","Id": "123abxy"} 

与以下端点:

case class aType(
    customUrl: Option[String], 
    Id:Option[String], 
    size:Option[String] 
) 

@ResponseBody 
    def addCompany(
    @RequestBody a: aType, 
    @ModelAttribute("action-context") actionContext: ActionContext 
): DeferredResult[Created] = Action[Created] 
{ 

    val customUrl = { 
     a.customUrl 
    } 

    val size = { 
     if (a.size == None) {None} 
     else Option(a.size.get.toLong) 
    } 

    val Id = { 
      a.Id 
    } 

    val handle = register(
     customUrl, 
     Id, 
     size 
    ).run() 

    }.runForSpring[Nothing](executors, actionContext) 

另外:

def register(
    customUrl: Option[String], 
    Id: Option[String], 
    size: Option[Long] 
) 

鉴于上述情况,我想知道正确的方法来处理sizecustomUrl未传递int的情况o POST正文。

在这种情况下,由于size可以是一个值(Long)或nullcustomUrl可以是Stringnull,我将承担适当的数据类型来处理,这将是Option[String]Option[Long]customUrlsize,分别。

我的问题是如何改变if-else条款来处理null或上述情景String/Long,这样我就可以通过有效的变量进入register(..)功能?

干杯,

回答

0

如果register函数接收大小和customURL作为选项,有什么问题呢?

我会做这样的事情:

@ResponseBody 
    def addCompany(
    @RequestBody a: aType, 
    @ModelAttribute("action-context") actionContext: ActionContext 
): DeferredResult[Created] = Action[Created] 
{ 
    val handle = register(a.customUrl,a.id,a.size).run() 

    }.runForSpring[Nothing](executors, actionContext) 

如果返回None如果size没有定义,那么一个要求:

@ResponseBody 
     def addCompany(
     @RequestBody a: aType, 
     @ModelAttribute("action-context") actionContext: ActionContext 
    ): DeferredResult[Created] = Action[Created] 
    { 

     val sizeOpt = a.size 

     val handle =sizeOpt.map { size => 
      register(a.customUrl,a.id,Some(size)).run() 
     } 

     }.runForSpring[Nothing](executors, actionContext) 

但即使是更好的,将是你的寄存器功能不期望Option s,并只处理原始类型。然后,你只需要映射3个可选值(我推荐使用的理解):

for { 
    size <- a.size 
    url <- a.customUrl 
    id <- a.id 
} yield register(url, id, size).run() 

与寄存器定义为:

def register(
    customUrl:String, 
    Id: String, 
    size: Long 
)