Is there a way for a class constructor to return a...
# announcements
p
Is there a way for a class constructor to return an optional type of itself? I would like the success of the constructor/init to be dependent on whether a network or db call succeeds or not. How would you otherwise handle this? With a factory pattern? Try/catch?
s
Make the constructor private and create a companion object that has a
operator fun invoke(....) : Option<MyClass>
This then becomes a factory method that looks like a constructor. Be careful using this pattern, though, as not to confound the users of your code….
p
Trying this right now
k
Another option is a top level function with an uppercase name, that will look like a constructor too.
p
@streetsofboston that actually worked perfectly! Thank you!
s
@karelpeeters Using that scheme causes the IDE (lint checker) to start screaming at you 🙂
k
Yeah that's true.
p
And nobody likes a screaming linter. I sure don’t 😁
Thanks!
s
Why have something that looks like a constructor behave completely different from a constructor?? Surprises while reading code is usually the definition of bad code. (I’d have no issue if you’d use this approach to return cached instances of the object itself, because this would be an implementation detail, that the invokee of your code doesn’t need to know/care about.)
👍 1
t
i wouldn’t recommend the “capitalise the first letter of the function name to look like a constructor” approach - it’s confusing to consumers of your code