Kotlin object: only one line of code can be used to create a secure singleton and one line of kotlin
By Antonio Leiva
Time: Jun 20,201 7
Link: https://antonioleiva.com/objects-kotlin/
The Kotlin object is another language element that Android Developers are not familiar with, because there is nothing like this in Java.
In fact,An object is a data type with a single implementation. So if we want to find something similar in Java, it will be the singleton mode. In the following content, we will compare them.
Examples and objects
In Java, Singleton is not as easy to implement as it sounds. It is generally considered as follows:
1 public class Singleton { 2 3 private Singleton() { 4 } 5 6 private static Singleton instance; 7 8 public static Singleton getInstance() { 9 if (instance == null) {10 instance = new Singleton();11 }12 13 return instance;14 }15 }
However, this code is dangerous, especially when used in different threads. If two threads access this Singleton at the same time,Two instances of this object may be generated.. The security code should be:
1 public class Singleton { 2 3 private static Singleton instance = null; 4 5 private Singleton(){ 6 } 7 8 private synchronized static void createInstance() { 9 if (instance == null) {10 instance = new Singleton();11 }12 }13 14 public static Singleton getInstance() {15 if (instance == null) createInstance();16 return instance;17 }18 }
As you can see, creating a valid Singleton requires several lines of code.
So what is in Kotlin?
1 object Singleton
You do not need more code. You can use the bytecode tool in Tools --> Kotlin to display it, and then use the Decomplie option. That is, you can see that the Kotlin team decides how to implement Singleton.
We recommend that you use this tool when you are not sure what is happening behind it.
Object Declaration
Declaring an object is like declaring a class.
As an example, let's declare an object that implements Database Help:
1 object MySQLOpenHandler : SQLiteOpenHelper(App.instance, "MyDB", null, 1) {2 3 override fun onCreate(db: SQLiteDatabase?) {4 }5 6 override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {7 }8 9 }
This code, you only need to use reserved wordsobjectSubstitutionclass. You only need to considerThe object cannot have constructors.Because we do not call any constructor to access them.
The object instance is created when we use it for the first time.. So here is a lazy instantiation: if an object will never be used, this instance will never be created.
Companion Object)
Each class can implement an associated object, which is the object shared by all instances of the class. It will be similar to static fields in Java.
Example:
1 class App : Application() { 2 companion object { 3 lateinit var instance: App 4 private set 5 } 6 7 override fun onCreate() { 8 super.onCreate() 9 instance = this10 }11 12 }
In this example, I createApplicationExtension (delivery) class, and incompanion objectIt is a unique instance.
lateinitThis attribute is not worthwhile at the beginning. However, it will be assigned a value before use (otherwise, an exception will be thrown ).
private setIt indicates that the external class cannot be assigned a value.
Note:
You may think that ifAppIs an object, rather than a class, it makes sense. In this case, because of the way the Android framework instantiates classes, when you try, you will find that an exception is thrown when the application starts. You needAppTo be a class, if you want to access it, you can create a small Singleton.
Object expression
Objects can also be used to create anonymous classes.
For example:
1 recycler.adapter = object : RecyclerView.Adapter() { 2 override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) { 3 } 4 5 override fun getItemCount(): Int { 6 } 7 8 override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder { 9 }10 11 }
For example, each time you want to create an inline implementation of an interface or expand another class, you will use the above symbol.
However, an object can also represent a non-existent class. You can create it in the run:
val newObj = object { var x = "a" var y = "b"} Log.d(tag, "x:${newObj.x}, y:${newObj.y}")
Conclusion
Objects are a new concept for Java 6 developers, but many concepts can be associated with existing ones, so you can quickly learn to use them.
If you like what you read, I suggest you read previous articles to learn more about Kotlin, or to learn how to create a complete application from the beginning.