https://kotlinlang.org logo
Title
g

Gus

03/30/2020, 5:03 PM
Hi. If I have a sub-class that sets a different companion object from its parent class, can a method on the parent class access the companion object of the current sub-class? Here's some code:
open 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?
s

Shawn

03/30/2020, 5:05 PM
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?
yes
g

Gus

03/30/2020, 5:06 PM
👍 thanks
s

Shawn

03/30/2020, 5:21 PM
spent a few minutes messing around in a scratch file, depending on what your requirements are for this hierarchy this may or may not be useful to you:
interface 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()
there’s no way to enforce that functionality is implemented by a companion object, but you can definitely choose to delegate out to it if you want
👏 2