are there any plans to allow a constructor for some class
MyClass
to return
MyClass?
that is, a constructor that can fail in ways that don't involve throwing exceptions?
as a trivial example, a
class NonZeroInt(n: Int)
that returns null if constructed with
n = 0
.
(I'm aware that I can do this with a
companion object
)
e
ephemient
03/04/2024, 7:56 PM
the object itself is constructed by the JVM, then the constructor is called; it can either return void (allowing the new object to be used) or throw. so any "constructor" that wants to
return null
would have to not go through a Java-compatible constructor pattern
ephemient
03/04/2024, 7:56 PM
and IMO we already have that pattern in Kotlin, with top-level functions named after the class itself
👆 3
ephemient
03/04/2024, 7:57 PM
(or
operator fun Companion.invoke()
, which you mentioned)
y
y
03/04/2024, 8:43 PM
thanks!
and I was actually unaware that top-level functions were idiomatic here.