Skip to content
This repository has been archived by the owner on Dec 21, 2023. It is now read-only.

Using factory functions #22

Open
yole opened this issue Jun 12, 2016 · 8 comments
Open

Using factory functions #22

yole opened this issue Jun 12, 2016 · 8 comments

Comments

@yole
Copy link
Contributor

yole commented Jun 12, 2016

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.

@damianw
Copy link

damianw commented Jun 13, 2016

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

@yole
Copy link
Contributor Author

yole commented Jun 14, 2016

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.

@voddan
Copy link

voddan commented Jun 14, 2016

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

@yole
Copy link
Contributor Author

yole commented Jun 14, 2016

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

@voddan
Copy link

voddan commented Jun 14, 2016

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

@yole
Copy link
Contributor Author

yole commented Jun 14, 2016

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.

@dstd
Copy link

dstd commented Aug 30, 2016

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

@MarcinMoskala
Copy link

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.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants