kotlin-style-guide
kotlin-style-guide copied to clipboard
Using factory functions
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.
Under what circumstances should the functions be in the companion object vs standalone? e.g. the stdlib uses listOf(...) rather than List.of(...)
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.
having big companion objects clutters the code, considering they are declared inside the class, not alongside (Scala)
If you find large companion objects to be a problem, you can extract code to extensions of companion objects.
Is it recommended to make factory functions as extensions on companion object?
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.
@damianw standalone functions has no access to private members of class
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.