What is the reason for classes not having a companion object by default?
Lately I have been very fond of using extension functions on the companion object in my tests to create convenient functions for creating test-data. I guess I could use context receivers but using the companion objects feels a lot cleaner in my opinion.
E.g.
Copy code
data class SomeComplexClass(…)
In test:
Copy code
fun SomeComplexClass.Companion.default(): SomeComplexClass = …
fun SomeComplexClass.Companion.random(): SomeComplexClass = …
Today I have to explicit add an empty companion object for this to be possible:
Copy code
data class SomeComplexClass(..) {
companion object
}
s
Stefan Oltmann
10/23/2024, 9:25 AM
I guess because that’s one instance of the class more on the heap that may often not be needed.
r
Robin T
10/23/2024, 9:27 AM
I guess it could have been possible to add optimization flags on the compiler 🤷 but I guess you are right