Should one include `companion object {}` in librar...
# announcements
h
Should one include
companion object {}
in library classes to support extension?
s
Out of curiosity, what benefits does this give you?
h
Well for example, if my library has a class
Point
and I include
companion object {}
, a user of the library could define
fun Point.Companion.fromJson(json: String) = // ...
allowing them to do
val p = Point.fromJson(json)
s
oh, I see, it’s a way to allow for pseudo-class-static extension methods
h
Exactly
And while I haven't created any myself I was giving a lecture on companion objects this week and it got me thinking that maybe I should include empty ones to allow for this
c
I’ve never considered that before, but I really like the idea!
h
Either I had until I was going through a similar example in class and I was like ya know that might be kinda handy
g
Hum, this is an interesting topic. If a third party class do not have a companion object, can we create a companion object extension for it?
h
Not that Im aware of
g
I was needing something like this to create some kotlin build scripts with kotlin dsl, this could be a good feature for us
s
I think the Arrow guys basically had a problem when Boolean didn't have a companion object for this exact reason. IIRC, the Boolean class got an empty companion object as a result.
h
I thought I vaguely recalled one of the "primitive" types not having one
l
You can use
companion object
without body if there's no declaration after it.
g
Hm. If you check
String
implementation in Kotlin it actually contains exactly this
companion object {}
.
h
@louiscad Intellij recommended that, required companion object; in most cases though
l
Yes, and now (as of 1.3.30 EAP), autocomplete no longer adds the braces