Gus
03/30/2020, 5:03 PMopen class TheCompanion(val foo: String)
open class Parent {
fun doIt(): String {
return foo
}
companion object : TheCompanion("the-parent")
}
class Child1() : Parent() {}
class Child2() : Parent() {
companion object : TheCompanion("child2")
}
Child1().doIt()
Child2().doIt()
How can I get Child2().doIt()
to output "child2"
instead of "the-parent"
?
I guess this isn't possible because there's no way to enforce that subclasses of Parent
must have a companion object implementing a given interface, right?Shawn
03/30/2020, 5:05 PMI guess this isn’t possible because there’s no way to enforce that subclasses of Parent must have a companion object implementing a given interface, right?yes
Gus
03/30/2020, 5:06 PMShawn
03/30/2020, 5:21 PMinterface HasFoo {
val foo: String
}
interface PrintsFoo : HasFoo {
fun printFoo(): Unit = println(foo)
}
class LeafA : PrintsFoo by Companion {
companion object : PrintsFoo {
override val foo = "LeafA"
}
}
class LeafB : PrintsFoo, HasFoo by Companion {
override fun printFoo() {
println("foo: $foo")
}
companion object : HasFoo {
override val foo = "LeafB"
}
}
LeafA().printFoo()
LeafB().printFoo()