kotlin-style-guide icon indicating copy to clipboard operation
kotlin-style-guide copied to clipboard

Using factory functions

Open yole opened this issue 9 years ago • 8 comments
trafficstars

If you declare a factory function for a class, don't give it the same name as the class itself. Use a distinct name making it clear why the behavior of the factory function is special. Example:

class Point(val x: Double, val y: Double) {
    companion object {
        fun fromPolar(angle: Double, radius: Double) = Point(...)
    }
}

If you have an object with multiple overloaded constructors that don't call different superclass constructors and can't be reduced to a single constructor with default argument values, prefer to replace the overloaded constructors with factory functions.

yole avatar Jun 12 '16 09:06 yole

Under what circumstances should the functions be in the companion object vs standalone? e.g. the stdlib uses listOf(...) rather than List.of(...)

damianw avatar Jun 13 '16 23:06 damianw

Good question. I'm not sure I have a good answer why the stdlib uses listOf as opposed to List.of(); my preference is to put factory functions into the companion object whenever possible.

yole avatar Jun 14 '16 10:06 yole

having big companion objects clutters the code, considering they are declared inside the class, not alongside (Scala)

voddan avatar Jun 14 '16 11:06 voddan

If you find large companion objects to be a problem, you can extract code to extensions of companion objects.

yole avatar Jun 14 '16 11:06 yole

Is it recommended to make factory functions as extensions on companion object?

voddan avatar Jun 14 '16 11:06 voddan

I don't think there is any need for specific guidance. The choice is the same as between making any other method a member of a class or an extension.

yole avatar Jun 14 '16 12:06 yole

@damianw standalone functions has no access to private members of class

dstd avatar Aug 30 '16 20:08 dstd

For the record, there are more ways to define factory functions in Kotlin:

  • Companion object factory function
  • Top-level factory function
  • Extension factory methods (Extension function to companion object)
  • Fake constructor (top-level function looking like a constructor) DSLs should be mentioned as well as a special kind of functions. Described them briefly here.

MarcinMoskala avatar Feb 16 '19 23:02 MarcinMoskala