https://kotlinlang.org logo
Title
c

Carl Hickman

01/17/2018, 7:59 PM
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

StavFX

01/17/2018, 8:01 PM
throw
?
c

Carl Hickman

01/17/2018, 8:03 PM
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

louiscad

01/17/2018, 8:04 PM
@Carl Hickman The
require(…)
methods from the stdlib are for you!
1
c

Carl Hickman

01/17/2018, 8:05 PM
Excellent, I’ll check those methods out!
j

Jonathan Ghazarian

01/17/2018, 8:08 PM
Oh nice, I didn't know about that one.
r

Ruckus

01/17/2018, 8:26 PM
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

cedric

01/17/2018, 8:39 PM
A builder is probably a better choice if constructing an object can fail
👍 3