gpt4 book ai didi

Scala:返回语句的问题

转载 作者:行者123 更新时间:2023-12-03 23:43:07 24 4
gpt4 key购买 nike

我对此有点困惑

以下代码编译正常:

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 语句,block 是返回直接执行 BadRequest 的结果...和 ​​Ok... 而不是返回将 block 传递给 Action 对象伴侣的结果...

我对吗?

注意:我试图找到一种方法来摆脱如此多的嵌套 map 和 getOrElse

ps:对不起,如果问题有点困惑,我自己也很困惑......

最佳答案

这两个表达式确实做了非常不同的事情!

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

在这里, save将返回 Action(Ok(toJson(Feature.find))) 的结果.现在,
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应该返回,所以它给出了一个类型错误。

记住: return从封闭的返回 def .

关于Scala:返回语句的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11929485/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com