-
Notifications
You must be signed in to change notification settings - Fork 14
Using factory functions #22
Comments
Under what circumstances should the functions be in the companion object vs standalone? e.g. the stdlib uses |
Good question. I'm not sure I have a good answer why the stdlib uses |
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:
|
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:
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.
The text was updated successfully, but these errors were encountered: