are companion objects overridable using inheritanc...
# announcements
x
are companion objects overridable using inheritance on data classes?
so you have data class Test (val a: String) with a companion object Test.companion.foo(test: Test){}
and want data class BetterTest which inherits from Test, but you want its companion object foo function to do something else
a
Companion objects are not inheritable at all (
BetterTest.Companion
) does not extend from
Test.Companion
. In fact, there isn't even a function called
BetterTest.foo(test: Test)
So, in your specific situation. Just go ahead and write the function on BetterTest Companion Object.
x
awesome, thank you!
and how do companion objects live? like if i declare a companion object in two diferent kt files with the same name, which one will be accessible from a third file?
so as an example, i have Test.companion.foo(){} declared on file x, from what i see i can access it on file y
a
You can think of Companion object as Java static classes. Difference is they are bound to a class. Because you can't have a companion object without first creating a class, and because you can't create more than one class of the same signature in the same package, you can't declare companion objects with same signature. However, while you can try to create two companion objects for one class, You will surely get a compilation error, even if they have different names
x
but what happens if i declare Test.companion.foo() on another file? which one will 'win'?
ah, i understand! that's what was not being clear to me, because i wasnt getting any errors on my ide itself
a
I am assuming this scenerio
Copy code
class Test(val a: String) {
    companion object {
        fun foo(t: Test){
          // do foo things
        }
    }
}

class BetterTest(override val a: String) : Test(a) {
    companion object {
        fun foo(t: Test) {
           // do foo-lish things
        }
    }
}

// To call foo from Test, you just type
Test.foo(Test("a")) // No need to type Test.Companion.foo(Test("a"))

//  To call foo from BetterTest you just type
BetterTest.foo(Test("a"))
BetterTest.foo(BetterTest("b")) //  since BetterTest extends Test
x
thank you, man!