james.cruz
12/19/2018, 6:28 AMobject
implementation.
What's the preferred way to get the implementation's instance?
1️⃣ Companion object as the default implementation
interface Foo {
companion object : Foo {
// default implementation goes here
2️⃣ Quasi constructor
interface Foo {
companion object {
operator fun invoke(): Foo = DefaultFooImpl
3️⃣ Top level method
fun defaultFoo(): Foo = DefaultFooImpl
Czar
12/19/2018, 10:54 AMjames.cruz
12/19/2018, 11:12 AMDefaultFooImpl
is an object
, so they're all returning the same singleton instance every time.
Regardless, 3️⃣ still seems to be the better choice, considering what you saidMike
12/19/2018, 1:54 PMdefaultFoo().someFunction()
, you can just do DefaultFooImpl.someFunction()
Or you want to be able to change the value of defaultFoo w/o having to change all occurrences throughout the code?
The use-case is unclear to me.james.cruz
12/20/2018, 2:18 AMinternal
object, as others have pointed out.
We're exposing an API to 3rd party users of our library. So we want to keep source and binary compatibility as much as possible.Czar
12/20/2018, 7:25 AMFoo.defaultSingletonImpl
interface Foo {
companion object {
val defaultSingletonImpl = DefaultFooImpl
}
}
bdawg.io
12/28/2018, 7:24 AMfun Foo(): Foo = DefaultFooImpl
(for example, emptySet()
returns a singleton of Set<Nothing>
)Job
which is an interface but you can get the default implementation using Job()