为什么在 Kotlin 的 Lambda 表达式中,try 块没有返回值?

huangapple go评论61阅读模式
英文:

Why is the try block not returning a value in a lambda expression in Kotlin?

问题

{
    message: Any ->

    try {
        ObjectMappers.getObjectMapper().writeValueAsString(message).toByteArray()
    }
    catch(e: JsonProcessingException) {
        e.printStackTrace()
    }
    null
},

然而,这段代码始终返回 null。在调试时,我发现程序执行进入 try 块并执行其中的代码,但随后还会执行位于 try catch 块之外的 null?为什么会发生这种情况?难道不应该从 try 块内部返回并退出 lambda 表达式吗?

(该表达式作为参数传递给一个期望函数值的函数)

英文:

I have the following code, where I am trying to return a value through a lambda expression.

{ message: Any ->

                    try {
                            ObjectMappers.getObjectMapper().writeValueAsString(message).toByteArray()
                        }
                        catch(e: JsonProcessingException)
                        {
                            e.printStackTrace()
                        }
                        null
                     },

However, the code always returns null. On debugging, I found that program execution is going through the try block executing its code but then also executing the null outside the try catch block? Why is this happening? Should it not return from inside the try block and exit the lambda expression?

(The expression is being passed as an argument to a function that is expecting functional values)

答案1

得分: 1

从最后一行删除那个 null。Lambda 中的最后一行指定了你要返回的值。由于你在最后一行写了 null,所以无论你的表达式执行什么操作,它总是会返回 null。

链接:https://kotlinlang.org/docs/reference/lambdas.html

英文:

Remove that null from the last line. Last line in lambda specify what value you are trying to return.Since you have written null as last line so whatever your expression perform it always return null .

https://kotlinlang.org/docs/reference/lambdas.html

答案2

得分: 0

从 lambda 中返回的是最后一行,所以在你的情况下始终为 null。

英文:

The last line from lambda is returned, so in your case is always null.

答案3

得分: 0

null 放在 catch 块内部。
try 是一个表达式,在 Kotlin 的 参考文档 中可以找到。

像这样:

try {
    ObjectMappers.getObjectMapper().writeValueAsString(message).toByteArray()
} catch(e: JsonProcessingException) {
    e.printStackTrace()
    null
}
英文:

Move null inside the catch block.
Try is an expression, can be found in kotlin reference

Like this:

try {
    ObjectMappers.getObjectMapper().writeValueAsString(message).toByteArray()
} catch(e: JsonProcessingException) {
    e.printStackTrace()
    null
}

huangapple
  • 本文由 发表于 2020年8月30日 22:08:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/63658287.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定