has there ever been an effort to free constructors...
# getting-started
y
has there ever been an effort to free constructors from requiring
: this(...)
, and just allowing any function which returns an instance of the class/object? in practice, I find this limitation of constructors makes them mostly useless, and so I'm forced to use companion objects or module-level free functions
e
except for lacking an equivalent of https://openjdk.org/jeps/447 (which if implemented in Kotlin would widen the https://youtrack.jetbrains.com/issues?q=tag:%20{use-before-initialization} issues), I don't think anything about constructors can change while being Java compatible
y
thank you for the pointer about "use before initialization". interesting.
r
I don't know if it addresses your issue exactly, but I've found that putting
operator fun invoke(...): MyClass
in the companion object works great. Doesn't have the limitations of a regular constructor, but it sure presents itself like a constructor
s
echoing what Ryan said—you can always write a factory method in the companion object that looks like a constructor. The decision to require invoking
this()
right in the secondary constructor signature is very deliberate and was done to avoid a whole host of initialization bugs. This doesn't make secondary constructors useless; it helps minimize their misuse.
y
personally I dislike
operator invoke
, because IDE support sometimes fails to jump to it, because it's operator overloading and especially because it's yet another competing Kotlin syntax for a class constructor. if I'm going to add a
companion object
"constructor", I prefer a descriptive name.