0

I'm trying to make a singleton in Kotlin and am running into problems because I get a smart cast to PresenterManager is impossible because instance is mutable property that could have been changed at this time.

This seems like a pretty standard way to make a singleton. Why won't it let me and how can I fix it?

PresenterManager {
    //some code
    ....

    companion object {
        private val PRESENTER_ID = "presenter_id"
        private var instance: PresenterManager? = null

        fun getManager(): PresenterManager {
            if (instance == null) {
                instance = PresenterManager(10, 30, TimeUnit.SECONDS)
            }
            return instance
        }
    }
}
Rafa
  • 3,219
  • 4
  • 38
  • 70
  • Kotlin already has Singleton implementation. Look at doc https://kotlinlang.org/docs/reference/object-declarations.html#object-declarations – vmtrue Nov 06 '17 at 02:05
  • Possible duplicate of [Smart cast to 'Type' is impossible, because 'variable' is a mutable property that could have been changed by this time](https://stackoverflow.com/questions/44595529/smart-cast-to-type-is-impossible-because-variable-is-a-mutable-property-tha) – BakaWaii Nov 06 '17 at 13:13

1 Answers1

2

This seems like a pretty standard way to make a singleton.

I do recommend you to read a bit more about Kotlin.

object PresenterManager {
    init {
       // init code
    }

    fun whatever() {}
}

What I wrote above is a Singleton in Kotlin. Now, to explain the message you are getting:

smart cast to PresenterManager is impossible because instance is mutable property that could have been changed at this time

instance is nullable (private var instance: PresenterManager? = null), and the getManager function expects a non-null return type, so one of the many ways of solving this is by either make getManager return a nullable type (fun getManager(): PresenterManager?) or make use of the !! operator on your return type.

The main point is that you really don't need of that instance variable at all if you use an object instead of a class to declare your singleton.

mradzinski
  • 614
  • 1
  • 8
  • 21
  • 1
    Or `instance` could be made non-null and [`lateinit`](https://kotlinlang.org/docs/reference/properties.html#late-initialized-properties) – ianhanniballake Nov 06 '17 at 02:47
  • It can also be lazy-instantiated using `by lazy { PresenterManager() }`. My point answering this question isn't about the options available for making `instance` non-null but to rather explain there's no need for it in first place and explain the reason behind the lint error :) – mradzinski Nov 06 '17 at 03:21