![]() ![]() And for the second scope function, run makes the most sense because it will not change the receiver from the outer scope, so it creates the least friction to readability here. apply would also work, but typically if you have a whole block of code to run, you don't want to be using it as a receiver. The also function doesn't return a result, but rather returns what it was called on, so there's no risk of accidentally triggering both scope functions. If myVar is a local variable (or a locally defined val property with no custom getter), you should do this: if (myVar != null). ![]() Note that in the top-voted answer that shows how it can be done, the advice is still to use if/else because that is more readable. A lot of new users excited about inline scope functions, and probably overly eager to use them as much as possible instead of just where they're the most appropriate tool. Have you tried debugging it to see what values are being returned Add some print or log statements You should probably read up on kotlin and null types. The question you linked is old, and from a time when there were a lot of new Kotlin users because of Android adopting it as a recommended language. Probably it means that it.get ('productImages') is returning null. Just because you can do something doesn't mean you should! Inline scope functions provide a lot of power, and therefore also a lot of potential for misuse and less readable code.įor example, the return value of the first scope function (if it is let or run) could potentially be null and cause the second scope function to also be run and return something else than you expected. For some simple actions you can use the safe call operator, assuming the action also respects not operating on an empty list (to handle your case of both null and empty: myList?.The best practice is to not chain scope functions with an Elvis operator to handle null/not null, because it is less readable and it is error-prone. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |