https://kotlinlang.org logo
Title
m

Mark

05/24/2020, 3:37 AM
In a companion object, is it acceptable practice for
operator fun invoke(...): MyClass?
to return a nullable value, or is that confusing to the caller since it looks like a constructor call?
j

Jakub Pi

05/24/2020, 4:51 AM
The type system will warn the client on use and force them to use either ? or !!... so it's legit if you need this capability. Though usually there is a cleaner design choice depending on the use case and the complexity you are willing to invest.
k

Kroppeb

05/24/2020, 10:25 AM
I've seen it suggested before.
m

Michael de Kaste

05/27/2020, 12:30 PM
Lets say we have an class that can be instantiated by giving a number between 0 and 1000, or a string that needs to contain at least an 'a' somewhere in it. There is no way to model this within a constructor and usually you'll just deal with it by throwing an error via the
require
statement. However, that's not always what you want from it. What if I just want to construct class instances where my inputs are correct, disregarding the other input. You'll have to catch the exception and unbox it again just to filter them out. I think in those cases I'd recommend the operator fun invoke constructors. An exception shouldn't be thrown in situations where you are aware of the input and output parameters and where returning null is acceptable.
j

Jakub Pi

05/27/2020, 2:00 PM
Other alternatives: Use
.from()
or
.of()
in your companion object instead of
operator invoke()
, especially in cases where you are doing an explicit conversion or if your type is an aggregate. You can also return an
Option<MyClass>
or
Either<SealedClassError, MyClass>
... Again these will require greater investment, but give your correspondingly more information and control. The
invoke()
with null is the simplest solution; start there and move up the complexity chain based on your requirements.
👍 1