Objects in Kotlin: Create safe singletons in one line of code
Kotlin objects are another element of the language that we Android developers are not familiarized with, because there is nothing like that in Java.
In fact, an object is just a data type with a single implementation. So if we want to find something similar in Java, that would be the Singleton pattern. We’ll compare them in the next section.
Singleton vs object
Singleton in Java isn’t as easy to implement as it sounds. One might think it’s as simple as this:
123456789101112131415 | publicclassSingleton{privateSingleton(){}privatestaticSingleton instance;publicstaticSingleton getInstance(){if(instance==null){instance=newSingleton();}returninstance;}} |
But this code is dangerous, especially if it’s used in different threads. If two threads access this singleton at a time, two instances of this object could be generated
123456789101112131415161718 | publicclassSingleton{privatestaticSingleton instance=null;privateSingleton(){}privatesynchronized staticvoidcreateInstance(){if(instance==null){instance=newSingleton();}}publicstaticSingleton getInstance(){if(instance==null)createInstance();returninstance;}} |
As you can see, you need a few lines to create a valid Singleton.
What would be the equivalent in Kotlin?
Want to learn Kotlin?
Check my free guide to create your first project in 15 minutes!
1 | objectSingleton |
You don’t need more. You could use the Show bytecode tool you can find at Tools -> Kotlin, and then use the Decompile option. That way, you can see what’s the implementation that the Kotlin team decided to use for singletons.
I really recommend using that tool when you’re not sure what’s happening behind the scenes.
Object declaration
Declaring an object is as simple as declaring a class.
Let’s declare for example an object that implements a database helper:
123456789 | objectMySQLOpenHandler:SQLiteOpenHelper(App.instance,"MyDB",null,1){override fun onCreate(db:SQLiteDatabase?){}override fun onUpgrade(db:SQLiteDatabase?,oldVersion:Int,newVersion:Int){}} |
As you can see, you just need to use the reserved word object
instead of class
and the rest is the same. Just take into account that objects can’t have a constructor, as we don’t call any constructors to access to them.
The instance of the object will be created the first time we use it. So there’s a lazy instantiation here: if an object is never used, the instance will never be created.
Companion Object
Every class can implement a companion object, which is an object that is common to all instances of that class. It’d come to be similar to static fields in Java.
An implementation example:
123456789101112 | classApp:Application(){companionobject{lateinit varinstance:Appprivateset}override fun onCreate(){super.onCreate()instance=this}} |
In this case I’m creating a class that extends Application
and stores it in the companion object
its unique instance.
The lateinit
indicates that this property won’t have value from the beginning, but will be assigned before it’s used (otherwise it’ll throw an exception).
The private set
is used so that a value can’t be assigned from an external class.
Note: You may think that it’d make a lot of sense for
App
to be an object instead of a class. And so it is, but due to the way the Android framework instantiate the classes, if you try, you’ll see that the application throws an exception when it’s launched. You’ll needApp
to be a class, and you can create this little Singleton if you want to access to it.
Object expressions
Objects can also be used to create anonymous class implementations.
An example:
1234567891011 | recycler.adapter=object:RecyclerView.Adapter(){override fun onBindViewHolder(holder:RecyclerView.ViewHolder?,position:Int){}override fun getItemCount():Int{}override fun onCreateViewHolder(parent:ViewGroup?,viewType:Int):RecyclerView.ViewHolder{}} |
Every time you want to create an inline implementation of an interface, for instance, or extend another class, you’ll use the above notation.
But an object can also represent a class that doesn’t exist. You can create it on the fly:
123456 | val newObj=object{varx="a"vary="b"}Log.d(tag,"x:${newObj.x}, y:${newObj.y}") |
Conclusion
Objects are a new concept for those of us coming from Java 6, but there are many ideas that can be associated with existing ones, so you’ll get fast with them.
If you like what you’ve read, I encourage you to take a look at the the previous articles where you can learn more about Kotlin, or in the book where you’ll learn how to create a complete App from scratch.
I’m in love with Kotlin. I’ve been learning about it for a couple of years, applying it to Android and digesting all this knowledge so that you can learn it with no effort.
SharesLike this:
Loading...Related
相關推薦
Objects in Kotlin: Create safe singletons in one line of code
Kotlin objects are another element of the language that we Android developers are not familiarized with, because there is nothing like that in Java.
Soft-NMS: Improving object detection with one line of code
Improving object detection with one line of code 是ICCV2017的文章,主要是優化解決目標檢測後處理中非極大值抑制(NMS,Non Maximum Suppression)的問題。 NMS: 在解析本文主治之前,先回顧下
fail-fast vs fail-safe iterator in Java
change size another cti acc 1.5 following provided there Reference [1] http://netjs.blogspot.co.uk/2015/05/fail-fast-vs-fail-safe-iterato
Cannot create __weak reference in file using manual reference counting
解決 msu prop nsobject -s xcod pos create mod Xcode更新到7.3後會出現NSObject+MJProperty.h報Cannot create __weak reference in file using m
LeetCode 562. Longest Line of Consecutive One in Matrix(在矩陣中最長的連續1)$
find ive col discus hint 分開 arr public 標簽 Given a 01 matrix M, find the longest line of consecutive one in the matrix. The line could be
leetcode562- Longest Line of Consecutive One in Matrix- medium
color 一個 mat etc 依賴 ould bound result 連續 Given a 01 matrix M, find the longest line of consecutive one in the matrix. The line could be h
LaTeX: two figures in one line (兩個圖片置於同一行)
\begin{figure} \centering \begin{minipage}{.33\textwidth} \centering {\includegraphics[width=0.944\linewidth]{./figures/illust
The CURD(增刪查改) operation of DataFrame in python[Create]
注:安裝pandas自行完成:pip install pandas! 一、Create(增加、建立DataFrame) 在pandas裡,DataFrame是最經常用的資料結構,這裡總結一下: ①、把其他格式的資料整理到DataFrame中; ②在已有的DataFrame中插入N列或者N行。 1. 字典型別讀
thread safe singleton in c++11
class CSingleton final { public : static CSingleton& GetInstance(); private
How To Create Custom Dialog In Android With Validation
Let’s learn how to create custom dialog in android and while we are at it, let us also do simple validation of the data the user entered before clicking
How do you create a dictionary in Java?
用習慣python的 dictionary, 到其他程式語言也會想要用一下。 You’ll want a Map<String, String>. Classes that implement the Map interface include (but are not limited to)
How would I create a UIAlertView in Swift?
let Msg:String = "Hello" let alert = UIAlertController(title: "Alert", message: Msg, preferredStyle: UIAlertControllerStyle.alert) alert.addActi
[LeetCode] Longest Line of Consecutive One in Matrix 矩陣中最長的連續1
Given a 01 matrix M, find the longest line of consecutive one in the matrix. The line could be horizontal, vertical, diagonal or anti-diagonal. Example:
Mystery of Saturn's moon Titan's atmospheric haze: A team of scientists homes in on a 'missing link' in Titan's one
Now, a research collaboration involving scientists in the Chemical Sciences Division at the Department of Energy's Lawrence Berkeley National Laboratory (
Create CRUD Application in Express JS
Create Data Access Object file :In the Data Access Object (DOA) layer, we can define the function which is directly connected to the database and fetch dat
Listeners with several functions in Kotlin. How to make them shine?
One question I get often is how to simplify the interaction with listeners that have several functions on Kotlin. For listeners (or any interfaces) w
generation mechanism discovered in 'rainbow' weevil: Similar structures could one day be used for brighter cosmetics and better
P. c. pavonius, or the "Rainbow" Weevil, is distinctive for its rainbow-coloured spots on its thorax and elytra. These spots are made up of nearly-circula
Operator overloading in Kotlin
Kotlin has a fixed number or symbolic operators we can easily use on any class. The way is to create a function with a reserved name that will be map
Sealed classes in Kotlin: enums with super
Sealed classes in Kotlin are another new concept we didn’t have in Java, and open another new world of possibilities. A sealed class allows you to re
Operator overload in Kotlin: Add standard operations to any class (KAD 17)
In Kotlin, as in every language, we have predefined operators to perform certain operations. The most typical are the addition (+), subtraction (-),