https://kotlinlang.org logo
Title
m

Matteo Mirk

04/20/2021, 3:00 PM
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?
2️⃣ 2
1️⃣ 1
e

ephemient

04/20/2021, 3:02 PM
not sure why you'd choose 1️⃣, top-level object is better than an empty class with a companion object
m

Michael Böiers

04/20/2021, 3:06 PM
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

Matteo Mirk

04/20/2021, 3:08 PM
@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

ephemient

04/20/2021, 3:08 PM
oh I see. eh... this really depends on how much Java compatibility you need
m

Matteo Mirk

04/20/2021, 3:08 PM
@Michael Böiers I see my question wasn’t clear enough, I’ll update it
m

Michael Böiers

04/20/2021, 3:11 PM
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

Matteo Mirk

04/20/2021, 3:13 PM
thanks for your feedback
e

ephemient

04/20/2021, 3:13 PM
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