ruclip
ruclip

Reputation: 778

"singleton" pattern method best way in kotlin

Can someone help me to find a better way to create a single instance in Kotlin?

class Bar(private val blub) {

   private lateinit var foo: FooService
   private lateinit var doo: DooService

   override fun getFooService(): FooService {
       if (!::foo.isInitialized) {
           foo = FooService(blub)
       }
       return foo
   }

    override fun getDooService(): DooService {
       if (!::doo.isInitialized) {
           doo = DooService(blub)
       }
       return doo
   }
}

Edit: I don't want to init every object at beginning - should be only done when needed.

Thanks in advance!

Upvotes: 2

Views: 3670

Answers (2)

Stanislav Mukhametshin
Stanislav Mukhametshin

Reputation: 853

Your class is not looking as singleton. Maybe you want something like this

class Bar(private val blub) {

    var foo by lazy{ FooService(blub) }
}

OR you can put it in companion object to have the same instance between all objects

Upvotes: 2

zsmb13
zsmb13

Reputation: 89528

If your FooService doesn't take any parameters via the getter for its initialization, you can use an object for this:

object FooHolder {
    val foo: FooService = FooService(...)
}

Otherwise, your pattern seems just fine, the alternative would be to use a nullable variable instead of lateinit, but they're essentially the same:

private var foo: FooService? = null

override fun getService(): FooService {
    if (foo == null) {
        foo = FooService(...)
    }
    return foo!!
}

Upvotes: 2

Related Questions