Search code examples
kotlinktor

Confused about elvis's it


I'm using ktor and for some reason, the elvis operator's it is the outer scope's it and not the left operand. Can someone help to explain?

enter image description here


Solution

  • The code to the right of a ?: is only called if the expression to the left of the ?: evaluates to null. So your second let only gets called if jwt is null, or if the lambda of the first let returns null.

    The code to the right of ?: therefore is evaluated completely independently from the code to the left. You're calling let on whatever this is.

    Your first let is called on jwt. The second let is called on whatever this is at that point. Notice there is no . before it. You're using the typical shortcut of omitting this. before a bare function call.

    It is inadvisable to chain scope functions with ?: because it is extremely error-prone and hard to read the code and interpret it correctly. One possible big pitfall is if your first lambda evaluates to null, you could be running both scope functions to the left and right of the ?: inadvertantly.