When translating a class’ static factory methods f...
# codingconventions
m
When translating a class’ static factory methods from Java (used to construct its instances, not the Factory pattern), what do you prefer to use and why? 1️⃣ companion object 2️⃣ top-level function At first [1] seems a direct translation and will be familiar to Java devs, while [2] gives the possibility to escape the class definition and even the same file (although extension function offer the latter benefit as well). What do you think feels more idiomatic Kotlin?
1️⃣ 1
2️⃣ 2
e
not sure why you'd choose 1️⃣, top-level object is better than an empty class with a companion object
m
If a function doesn’t need any state (properties), then it should stand alone. If it does, then you can put it into an object (singleton) along with the required properties. 🙂
In other words: I wouldn’t want to use an object, companion or otherwise, merely as a namespace for functions. We already have packages for that.
m
@ephemient no, 1️⃣ refers to a companion object in the class to be constructed. I’m referring to static factory methods of a class, not the Factory pattern. Sorry if it was unclear
e
oh I see. eh... this really depends on how much Java compatibility you need
m
@Michael Böiers I see my question wasn’t clear enough, I’ll update it
m
I see. Not sure, I would still lean towards standalone functions even for factory methods. Putting them inside the implementation class would be kind of messy. They should go with an interface, or outside, leaving the implementing class internal to the package.
m
thanks for your feedback
e
unless you need to keep the interface
Foo.makeFoo()
or something like that for Java compatibility reasons, in which case you have no choice but to use
class Foo { ... companion object { @JvmStatic fun makeFoo() ... } }
👌 1