Any way to ‘fail’ the instantiation of a Kotlin cl...
# announcements
c
Any way to ‘fail’ the instantiation of a Kotlin class? I would like to fail instantiation in case certain constructor parameters are not valid.
s
throw
?
c
Perhaps. I’m looking at porting some swift code that allows constructors to throw nil. I’ll see if I can just catch instead. Thanks!
l
@Carl Hickman The
require(…)
methods from the stdlib are for you!
1
c
Excellent, I’ll check those methods out!
j
Oh nice, I didn't know about that one.
r
If it's just doing bounds checking and the like (things that should pretty much always be true),
require
is the way to go. If you expect it to be null regularly, I'd recommend helper functions on the companion object. Generally you don't expect constructors to fail.
👍 1
c
A builder is probably a better choice if constructing an object can fail
👍 3