The missing ? trap in Kotlin

Beware of this trap. Check out the below seemingly improved Kotlin code

// Original code
if (someObject != null && status) {
doThis()
}
// Improve code (but return wrong result!!)
someObject?.takeIf{ status }.apply{ doThis() }

What’s wrong with the code? Note: there is no compile error and it is still executable (no Null Pointer Exception as well).

--

--

--

Sharing iOS, Android and relevant Mobile App Development Technology and Learning

Recommended from Medium

How to use format(), an in-built function in Python

Implementing SMS Verification with Huawei SMS Retriever

A real f*cking explanation of “it’s deprecated”…

7 Weeks Career Transformation Challenge with Python

Distributed Database Management Systems

Who are High Level Actors involved in Era Swap | Mission & Vision

DDD modelling beyond software

Is your Code Solid Enough? — Part 1

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Elye

Elye

Sharing Software Development Experience, focus on Mobile. https://elye-project.medium.com/subscribe https://twitter.com/elye_project

More from Medium

Comparing Android LiveData and StateFlow

How To Test Kotlin Coroutines?

People creating

Exo-Player — The DRM Way(Part III)

Jetpack DataStore in Modern Android Development