-2

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)

shreyasm-dev
  • 2,711
  • 5
  • 16
  • 34
Denise
  • 898
  • 1
  • 16
  • 30

3 Answers3

1

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

Dhirendra Gautam
  • 737
  • 8
  • 16
0

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

Ice
  • 1,783
  • 4
  • 26
  • 52
0

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
}
Deadbeef
  • 1,499
  • 8
  • 20