In our daily coding, we mostly use these data types String, Boolean and List. There are many checks, we need on these data types but it is not present in their respective classes.
Checks, we use mostly like null, ifTrue, ifFalse, hasElements etc. We generally use objects, when there is some data in it. There is no use of Null object or an empty list except showing error message.
So, we will create some or few extension functions for these datatypes and can easily be called on their respective objects even on Null.
Extension function has Very Important Feature as…
We use multiple classes for creating objects and using its properties. These classes are sometimes in-scope of developer, means we can modify or extend class definition as per new requirements. But, they are some classes where we have no control to even look into it. Library classes are not in scope of modification. While, Final classes are not in scope of inheritance. For Example, String class can neither be modified nor extended.
So, Kotlin provides mechanism of “Extension Function” to add more features to existing class. It will act same as member function, but it will NOT be a part…
Singleton is part of creational design pattern. It serves to create one and only one instance of class. It is mainly used in web service call, database call. In multi-threading, if there are multiple instance of database object, then many threads can Write at same time into database. It will leave database with wrong data. So, Singleton pattern is used to avoid such scenario.
In Java, singleton is implemented using following basic rules.
In Kotlin, variables are declared by keyword val and var. There is much care has been taken to reduce NullPointerException. There are two type systems that can hold a null value or not. A regular variable type can NOT hold null value.
To store a null value, variable needs to be declared nullable as String?
To access nullable variables, we use Safe Call. If variable is not null, it will execute the right side of ?. operator. If variable is null it will not execute right side (returns null) and does not throw NullPointerException.
It is more…
We have seen how to create Singleton object in Java
Purpose of Singleton is to create one and only one instance of class.
There are three techniques, by which application can break Singleton pattern. It will create more than one object of singleton class. Hashcode is used to check if there are more than one objects. If hashcode of two instance is different, then there are two different objects.
Using reflection, application can call constructor directly.
Solution to Reflection.
Using Object class method clone(), we can create clone (or different object) of same class.