Is there a way to add a companion object to a clas...
# announcements
e
Is there a way to add a companion object to a class from another library. So that i can add extension methods to it. Trying to find a nice way to do SomeDtoClass.generate(10) for a testing solution. Or are there som other nice way?
🚫 1
b
Nope, original author must leave
companion object
in the class for you to extend
e
Thank, looks like a popular one. Ill look for another way to get clean code for doing what i want
s
Worth mentioning that if you already do have a companion object on your type, you can add extensions to that one:
Copy code
class Foo {
    companion object
}

fun Foo.Companion.bar() { println("bar") }

fun main() {
    Foo.bar()
}
But that, of course, requires that you control the type in question, which might not be your case.
e
Ended up doing a class to add the extension to. Generator<T> whit a companion object. So i get Ganerator<DTO>(seed).generate(5). It ended up whit about the same readability.
n
Just out of pure curiosity, why not generate<DTO>(seed, 5)
e
Makes it harder to extend. Having the Generator object makes it posible to do fun Generator<Dto2>.generate() and keep the code close to the type.