Page 1 of 1

Property Order in Kotlin - Why It Matters

Posted: Mon Dec 23, 2024 5:24 am
by rakibhasan
Writing Android apps in Kotlin is nice, as it’s easy to learn, especially when we know Java. Yet there are some traps we can fall into. Today, I would like to show you one related to Kotlin properties. We will also look into the bytecode.


Order of Class Properties
Actually, in most cases, tools embedded in IDEs like Android Studio or Intellij are very helpful but sometimes they can mislead us. Let’s assume that we have the following class:

It’s quite simple, isn’t it? But there bulk mobile database is a snag in this code, because when we call println(Foo().product) we will get 0 instead of 2. Although isValid seems to be true, in actuality when the product is evaluated, the isValid property isn’t initialized yet and returns false, so number returns 0.

Even the lint shows us a misleading hint. When we make a quickfix using Alt+Enter and selecting Simplify expression, we will get get() = 1 so the code behavior will change.