WISHY
WISHY

Reputation: 11999

Correct way of using singleton in kotlin?

I have a singleton class as follows

object SharedPrefTask {

fun doSomeWork() {
    ....
    ....
}}

I am using the method doSomeWork in 2 ways. Approach 1

private var prefTask: SharedPrefTask = SharedPrefTask
prefTask.doSomeWork()

Approach 2

SharedPrefTask.doSomeWork()

Which is the correct approach here?

Upvotes: 0

Views: 118

Answers (1)

Sage
Sage

Reputation: 106

Both are technically correct and will have the same outcome. When you use your first approach prefTask: SharedPrefTask = SharedPrefTask all you're really doing is making a variable that references the object. So if you were to call prefTask.doSomeWork() it would be the exact same as calling SharedPrefTask.doSomeWork().

Knowing this, it seems like it would be best to just go with your second approach since it is more clear and uses less code.

Upvotes: 1

Related Questions