Scala:return语句出现问题 [英] scala: problems with return statement

查看:93
本文介绍了Scala:return语句出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对此有些疑惑

以下代码可以编译:

def save: Action[AnyContent] = Action {
  if (1 == 2) {
    BadRequest(toJson("something went wrong"))
  } else {
    Ok(toJson(Feature.find))
  }
}

但是如果我只添加return语句,则会得到以下信息:

but if I just add the return statement, I get the following:

def save: Action[AnyContent] = Action {
  if (1 == 2) {
    return BadRequest(toJson("something went wrong"))
  } else {
    return Ok(toJson(Feature.find))
  }
}

[error]  found   : play.api.mvc.SimpleResult[play.api.libs.json.JsValue] 
[error]  required: play.api.mvc.Action[play.api.mvc.AnyContent]
[error]       return BadRequest(toJson("something went wrong"))

我认为这两个代码是等效的...

I thought this two codes would be equivalent...

顺便说一句,Action是一个伴随对象,带有一个apply方法,该方法接收以下形式的函数:Request [AnyContent] =>结果,并返回Action [AnyContent]

BTW, Action is a companion object, with an apply method that receives a function of the form: Request[AnyContent] => Result, and that returns an Action[AnyContent]

似乎使用return语句,该块返回的是直接执行BadRequest和Ok的结果,而不是返回将该块传递给Action对象同伴的结果.

It seems like with the return statement, the block is returning the result of directly executing BadRequest... and Ok... instead of returning the result of passing the block to the Action object companion...

我说得对吗?

注意:我正在尝试找到一种方法来摆脱很多嵌套的地图和getOrElse

Note: I'm trying to find a way of getting rid of so many nested map and getOrElse

ps:很抱歉,如果这个问题有点令人困惑,我很困惑……

ps: sorry if the question is a little confuse, I'm confused myself...

推荐答案

这两个表达式确实做的很不一样!

These two expressions do very different things indeed!

def save: Action[AnyContent] = Action {
  if (1 == 2) {
    BadRequest(toJson("something went wrong"))
  } else {
    Ok(toJson(Feature.find))
  }
}

在这里,save将返回Action(Ok(toJson(Feature.find)))的结果.现在,

Here, save will return the result of Action(Ok(toJson(Feature.find))). Now,

def save: Action[AnyContent] = Action {
  if (1 == 2) {
    return BadRequest(toJson("something went wrong"))
  } else {
    return Ok(toJson(Feature.find))
  }
}

这里的情况更加复杂.当评估return Ok(toJson(Feature.find))时,它将从save 返回!也就是说,Ok(toJson(Feature.find))传递给Action.取而代之的是,方法save的执行将停止并且将返回Ok(toJson(Feature.find))作为其结果-除了不是save类型应该返回的类型之外,因此会给出类型错误.

The situation here is more complicated. When return Ok(toJson(Feature.find)) is evaluated, it will return from save! That is, Ok(toJson(Feature.find)) will not be passed to Action. Instead, the execution of the method save will stop and Ok(toJson(Feature.find)) will be returned as its result -- except that this is not the type save is supposed to return, so it gives a type error.

请记住:return从随附的def返回.

Remember: return returns from the enclosing def.

这篇关于Scala:return语句出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆