The beauty of Kotlin Objects.
What are Objects?
Objects are similar to classes in that they can contain variables and functions, the difference is that everything inside objects is accessible by any class within the same package as the object. This means that multiple classes can access, and modify the variables inside the object. Objects are very good for memory optimization as they are lazily called when they are needed. In the following example we will create a basic User profile using a person Object to demonstrate how objects work. Lets dive into some code.
How to use Objects.
As you can tell from the code above objects in Kotlin can contains variables, and functions just like classes. In this example I am using lateinit to tell the compiler that we will initialize these variables later. This is not mandatory, but for tutorial purposes it saves time.
In the code above we call the variables from the person object. To call an objects functions or variables simply call object name followed by the period and than the variable or function you wish to call. If you are using IntelliJ, or Android Studio you should get a list of all the items in your object for you to chose from just like the image bellow.
To get the list of items from my object all I did was type “person.” then all the objects contents appear for me to select just like the image above. I personally enjoy using objects because it is a great way of organizing public variables instead of calling classes from other classes which can get a bit messy if you are calling sub classes. In the image bellow I will show you how calling a function from an object looks like, and how clean the code syntax is.
The function called above is a simple setter function that allows for you to set all the variables in one go without having to call each variable individually. Objects can be called many times so you may see something like this when initializing a ListView in Android.
Rules to follow:
DO NOT store API Keys in Objects
DO NOT replace classes for Objects, that is not the point of Objects.
TRY to make your Object names as short and descriptive as possible, just like classes.
Thank you for following my tutorial. If you enjoy my content follow me on Twitter to receive updates when a new article is released. Have a great day.