从 Kotlin 中的 lambda 表达式显式返回
Explicitly returning from lambda expression in Kotlin
使用 Spark,我得到了一些这样的代码:
post("/auth/login", { req, res ->
val body = parseBody(req.body())
val assertion = body["assertion"]
if (assertion == null) {
halt(400)
return null
}
// ...snip...lots more code
})
效果很好,除了...它无法编译——我得到 'return' is not allowed here
。
我 可以 将 lambda 的其余部分放在 else
块中,但为了最小化缩进,我宁愿不这样做。
那么我如何 "short circuit" 将 lambda 转换为 return 空值?
我发现这似乎可行,尽管有点冗长:
post("/auth/login", fun(req, res): Any? {
val body = parseBody(req.body())
val assertion = body["assertion"]
if (assertion == null) {
halt(400)
return null
}
// ...snip...lots more code
return null // or whatever
})
据我了解,Lambda 不能使用 return,return 默认用于函数。
所以你需要使用标签来告诉 return 子句它将 return 到哪里。
我用这个:
f@ {
...
return@f null
}
使用 Spark,我得到了一些这样的代码:
post("/auth/login", { req, res ->
val body = parseBody(req.body())
val assertion = body["assertion"]
if (assertion == null) {
halt(400)
return null
}
// ...snip...lots more code
})
效果很好,除了...它无法编译——我得到 'return' is not allowed here
。
我 可以 将 lambda 的其余部分放在 else
块中,但为了最小化缩进,我宁愿不这样做。
那么我如何 "short circuit" 将 lambda 转换为 return 空值?
我发现这似乎可行,尽管有点冗长:
post("/auth/login", fun(req, res): Any? {
val body = parseBody(req.body())
val assertion = body["assertion"]
if (assertion == null) {
halt(400)
return null
}
// ...snip...lots more code
return null // or whatever
})
据我了解,Lambda 不能使用 return,return 默认用于函数。
所以你需要使用标签来告诉 return 子句它将 return 到哪里。 我用这个:
f@ {
...
return@f null
}