Singleton with parameter in Kotlin

后端 未结 11 1130
无人及你
无人及你 2020-11-30 21:51

I am trying to convert an Android app from Java to Kotlin. There are a few singletons in the app. I used a companion object for the singletons without constructor parameters

11条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-30 22:29

    If the only parameter you need is the application Context, then you can initialize it to a top level val, early in a ContentProvider, like the Firebase SDK does.

    Since declaring a ContentProvider is a bit cumbersome, I made a library that provides a top level property named appCtx for all places where you don't need an Activity or other special lifecycle bound context.

提交回复
热议问题