Is there other ways to access delegated object tha...
# getting-started
k
Is there other ways to access delegated object than list it in the primary constructor? Basically I'm doing like this:
Copy code
interface ISome 
class SomeImpl: ISome {
  fun doOtherThingsNotInISome() {...}
}
class Component(private val some: SomeImpl = SomeImpl())
  : ISome by some {
  fun main() {
    some.doOtherThingsNotInISome()
  }
}
r
If you want to use
some
in
Component
then I don't think there's any other way. Although, if you don't need the reference to the delegate, but you only want to specify a common functionality of the interface to reuse easily, then you can instantiate the delegate at place.
Copy code
class Component : ISome by SomeImpl() {...}
thank you color 1
k
Thank you, that's what I was doing initially. But eventually there're some internal states inside
some
I'd like to change but don't want to expose that in delegating class. The use case for this is that I want to gather some capabilities implementation inside a class and reuse it in multiple places, consider this:
Copy code
interface HasDialog {
    fun onShowDialogClick()
    fun onDialogBtnClick()
}
class DialogImpl : HasDialog {
    private val dialogCtrl = MutableStateFlow(false)
    
    override fun onShowDialogClick() = show()
    override fun onDialogBtnClick() = dismiss()

    fun dismiss() { dialogCtrl.value = false }
    fun show() { dialogCtrl.value = true }
}
interface Component: HasDialog {
  fun actionA()
}
class ComponentImpl(val dialogImpl: DialogImpl= DialogImpl()): Component, HasDialog by dialogImpl {
    override fun actionA() {
        //...
        dialogImpl.dismiss()
    }
}
a
would adding
fun doOtherThingsNotInISome()
to
interface ISome
be possible? I’m curious, because maybe there’s another way of solving the problem you’re trying to solve
k
Yes, that's one of the solutions I'd (unwillingly) use. But that'll add a lot burdens when subclassing (I.e creating Fake implementation of
Component
etc), since I'd intend to make Component implements several capabilities, (HasDialog, HasSnackBar etc...) (sorry I've editted the above comment)
In general I'd like to hide implementation details as much as possible.
a
since Component implements HasDialog,
Copy code
class ComponentImpl(val dialogImpl: DialogImpl= DialogImpl()): Component, HasDialog by dialogImpl
could be simplified to
Copy code
class ComponentImpl(val dialogImpl: DialogImpl= DialogImpl()): Component by dialogImpl
Which doesn’t help much - just making an observation :)
In general I’d like to hide implementation details as much as possible.
Are you trying to hide implementations just internally to make the code cleaner & simpler, or are you publishing a library and you want to hide things from library users?
k
I'm just hide implementations internally (to make the code cleaner & simpler -> Yes 😉 )
💯 1