scala:返回语句的问题
我对此有点困惑 以下代码编译为ok:scala:返回语句的问题,scala,playframework-2.0,Scala,Playframework 2.0,我对此有点困惑 以下代码编译为ok: def save: Action[AnyContent] = Action { if (1 == 2) { BadRequest(toJson("something went wrong")) } else { Ok(toJson(Feature.find)) } } 但如果我只添加return语句,我会得到以下结果: def save: Action[AnyContent] = Action { if (1 == 2) {
def save: Action[AnyContent] = Action {
if (1 == 2) {
BadRequest(toJson("something went wrong"))
} else {
Ok(toJson(Feature.find))
}
}
但如果我只添加return语句,我会得到以下结果:
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"))
我以为这两个代码是等价的
顺便说一句,Action是一个伴随对象,它有一个apply方法,该方法接收以下形式的函数:Request[AnyContent]=>Result,并返回Action[AnyContent]
似乎在return语句中,块正在返回直接执行BADDREQUEST的结果。。。好的。。。而不是返回将块传递给动作对象同伴的结果
我说得对吗
注意:我正试图找到一种方法来摆脱这么多嵌套的map和getOrElse
ps:抱歉,如果问题有点混乱,我自己也很困惑…您使用的方法确实是在
操作
同伴对象中定义的,但它不是您在问题中描述的方法,而是:
def apply (block: ⇒ Result): Action[AnyContent]
参数(block
)是一个result类型的表达式,稍后将根据需要进行计算(按名称计算)。它不是一个函数或闭包,只是一个表达式。因此,您不能从表达式返回
顺便说一句:在Scala中使用return
是一种代码味道,应该避免使用。这两个表达式确实做了非常不同的事情
def save: Action[AnyContent] = Action {
if (1 == 2) {
BadRequest(toJson("something went wrong"))
} else {
Ok(toJson(Feature.find))
}
}
在这里,save
将返回操作的结果(Ok(toJson(Feature.find))
。现在,
def save: Action[AnyContent] = Action {
if (1 == 2) {
return BadRequest(toJson("something went wrong"))
} else {
return Ok(toJson(Feature.find))
}
}
这里的情况更为复杂。当计算返回Ok(toJson(Feature.find))
时,它将从保存返回!也就是说,Ok(toJson(Feature.find))
将不会被传递到Action
。相反,方法save
的执行将停止,并且Ok(toJson(Feature.find))
将作为其结果返回——只是这不是save
应该返回的类型,因此它给出了一个类型错误
记住:return
returns from the encloseddef
我不知道函数和表达式之间的区别,我会用谷歌搜索它。。。顺便说一句,也许你可以帮我回答这个问题,这就是开始这一切的原因:@opensas你应该检查的区别是“函数”和“按名称调用参数”。按名称调用以=>
@paradigmatic开头,因此您的意思是返回
需要包含方法
(方法保存
,类型为操作[AnyContent]
),而不是操作
所期望的类型(类型为Result
,或编译器报告的SimpleResult
)。或者,换句话说,“您不能从表达式返回”,但您可以(并且编译器尝试)从方法返回。有意义,谢谢。谢谢daniel,我发现了你所说的困难的方法…有没有同样的方法可以无条件退出函数?也就是说,我希望返回在传递给Action的块中进行计算…@opensas你可以始终将你的函数定义为def
,然后将其作为段落传递仪表至操作
。记住:从随附的def返回值。请您解释一下这是什么意思?@Alex这太长了,无法发表评论。问一个问题。