https://kotlinlang.org logo
Title
l

Leoboyean

08/21/2019, 10:31 PM
Hello everyone, Someone can tell me wich is the best way to create a singleton, I had read something about "by lazy" but also another property like by DelegatesExt.notNullSingleValue()
m

mbonnin

08/21/2019, 10:33 PM
object Singleton {
}
👍 5
l

Lou Morda

08/21/2019, 10:35 PM
Also could use
companion object
... "The companion object is a singleton, and its members can be accessed directly via the name of the containing class" https://kotlinlang.org/docs/tutorials/kotlin-for-py/objects-and-companion-objects.html
l

Leoboyean

08/21/2019, 10:39 PM
Thanks a lot, but what happen when I do an instance of the Singleton object, Need I use the property "by Lazy" or "by DelegatesExt.notNullSingleValue()" in my object?
m

Mark Murphy

08/21/2019, 10:47 PM
If you use
object Singleton
, you just refer to
Singleton
. So, for example, if you had:
object Singleton {
  fun doSomethingTrulyAwesome() {
    TODO()
  }
}
...then elsewhere you could just call
SIngleton.doSomethingTrulyAwesome()
. However, manual singletons (such as
object
) are not very flexible, particularly when it comes to testing. You might want to look into "dependency inversion" options, such as Koin or Kodein, at some point.
👍 1
p

Paul N

08/22/2019, 8:58 AM
If you start using singletons a lot, as Mark Murphy said, consider a dependency injection framework such as Spring, which by the way has first class support from creating singletons via annotations, or programmatically. See https://spring.io/blog/2017/08/01/spring-framework-5-kotlin-apis-the-functional-way