Antoine Gagnon
12/01/2020, 9:35 PMopen class AnimalBuilder {
val dog: DogBuilder get() = DogBuilder()
open inner class DogBuilder : AnimalBuilder() {
val pug: PugBuilder get() = PugBuilder()
inner class PugBuilder : DogBuilder()
}
}
val pugBuilder = AnimalBuilder().dog.pug
val wrongBuilder = AnimalBuilder().dog.dog.dog
But as you can see, I don’t want the DogBuilder
to be able to access the dog
variable available in AnimalBuilder
. Is there any way to do that?mazorius
12/01/2020, 9:44 PMprivate val dog: DogBuilder get() = DogBuilder()
Antoine Gagnon
12/01/2020, 9:58 PMAnimalBuilder().dog
for instanceJoris PZ
12/01/2020, 10:04 PMMarc Knaup
12/01/2020, 10:17 PMinterface
for each and the classes and class hierarchies are merely an implementation detail. Then you are way more flexible in composing different interfaces and the functionality each has.
If you really want to keep it like it is then you can hide dog
in the subclass by overriding it.
1. Mark the dog
in AnimalBuilder
as open
.
2. Add inaccessible dog
to `DogBuilder`:
@Deprecated(message = "You already have a dog.", level = DeprecationLevel.HIDDEN)
override val dog: Nothing
get() = error("Cannot be used.")
DogBuilder
is inner
in AnimalBuilder
and also a subclass of AnimalBuilder
. So it’s linked to two different AnimalBuilder
instances 🤔Antoine Gagnon
12/01/2020, 10:20 PMopen class AnimalBuilderBase(parent: AnimalBuilderBase? = null)
open class AnimalBuilder : AnimalBuilderBase() {
val dog: DogBuilder get() = DogBuilder(this)
open class DogBuilder(parent: AnimalBuilder) : AnimalBuilderBase(parent) {
val pug: PugBuilder get() = PugBuilder(this)
class PugBuilder(parent: DogBuilder) : AnimalBuilderBase(parent)
}
}
Marc Knaup
12/01/2020, 10:21 PMAntoine Gagnon
12/01/2020, 10:24 PMAnimalBuilder().dog.pug
I would get Dog - Pug
but for AnimalBuilder().dog.greyhound
I would get Dog - Greyhound
with the DogBuilder level adding only the “Dog” string and the PugBuilder level adding the “Pug” stringMarc Knaup
12/01/2020, 10:25 PMAntoine Gagnon
12/01/2020, 10:26 PMbuild
function that would be part of AnimalBuilderBase
and would return the concatenation of all of thoseMarc Knaup
12/01/2020, 10:30 PMtoString()
but you can also use build()
.Antoine Gagnon
12/01/2020, 10:35 PM