is `companion object` the kookiest kotlin-specific...
# announcements
h
is
companion object
the kookiest kotlin-specific syntax for a typical OOP language feature? y/y?
c
It’s borrowed from Scala, but it actually turns out to be really useful beyond just “different syntax for static”. One particularly nice feature is that they can implement interfaces, making standardized class factories really nice (Ktor does this very well)
h
i completely, agree, other casey! i actually love it, but it was the strangest syntactical difference between languages like java/c++/c# that i had to get used to.
😂 3
j
The only thing that would make them better is if they were merged with their KClass more like Python and it's meta classes.
c
Is there anything preventing that?
(I mean, other than them actually implementing it that way)
j
I have no idea. For one, it would likely mean you could no longer extend a base class with a companion object, only implement interfaces and declare your own stuff. Maybe that's not so terrible, though...
n
I wish a companion object was always available even if not declared. A neat API convention is to define extension methods on <Type>.Companion (HTTP4K does this, for example) but it only works if the type has already declared a companion object.
👍 6
c
Seems like merging when it's a simple
companion object
and not when it falls into one of the more rare and complex cases would be useful.
h
@natpryce @jw wouldn't both those things break existing code?
j
Yep!
h
Backwards compatibility is, I imagine, the biggest reason so many programming languages exist.
j
Andrey has talked about an incompatible Kotlin 2.0 multiple times. Also hasn't stopped Apple breaking the entire language yearly. Swift is only getting more fans as a result.
🤔 1
h
Cool!
@jw i can't stop thinking about your comment about companion object having access to metadata. that would be so wonderful. they're so close to it. a lot of the time i skip the class syntax and just implement "constructors" via the invoke operator in the companion object. you can validate arguments there before instantiating the object, so it might even be better than standard class constructors. i digress