Android Dev Tips: Kotlin get
Simple code is preferred by software engineers. Simpler codes are often more effective, perform better, and most importantly, are simpler to read.
Kotlin, the de facto language for Android development, includes a variety of techniques for reducing code length. However, we must fully comprehend how each of them serves a unique purpose. We don't want to unintentionally create a bug.
I apologise for the pop culture allusion. As you can see above, the shorthand for the getRepulsorsStatus method is val repulsorsStatus. Using the get() method, as demonstrated below, is another technique to condense the code.
They both executed successfully. What’s difference ? Why do we need to use get ? When you use the method, you will be aware. IronManMk2 code will execute without bug. However, if I add another method to debug IronManMk1 code:
After that I call the shoot method. It will return with this response:
Jarvis: There is a bug. In order to be fixed, Iron Man must go back to the Avengers base.
What has truly occurred?
When we initiate IronMan class it will initiate the repulsorsStatus variable. This call is part of Kotlin class initialization. Therefore, It is important to put get() as it will make sure the code is only called when it is needed and not produce bug.
Alright that’s all I have for now. If you are looking unit test android then you might want to check this awesome blog on android tests
The views expressed on this blog post are mine alone and do not necessarily reflect the views of my employer, Optus Administration Pty Ltd.