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?
Thank, looks like a popular one. Ill look for another way to get clean code for doing what i want
s
sindrenm
04/19/2021, 2:36 PM
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
Eivind
04/19/2021, 4:31 PM
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
Nir
04/19/2021, 11:58 PM
Just out of pure curiosity, why not generate<DTO>(seed, 5)
e
Eivind
04/20/2021, 10:00 AM
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.