https://kotlinlang.org logo
Title
x

xenoterracide

04/30/2019, 6:50 PM
site = <http://dto.site|dto.site> ?: <http://this.site|this.site>!!
is this the best way to say use first if not null else use second if that also is null thow?
k

kevinherron

04/30/2019, 6:52 PM
i would use:
site = <http://dto.site|dto.site> ?: <http://this.site|this.site> ?: throw FooEx()
i suppose that's a matter of style, but any time I use
!!
and it fails it's a programming error
x

xenoterracide

04/30/2019, 6:54 PM
fair, in this case it would be a configuration error
k

kevinherron

04/30/2019, 6:55 PM
do you have a better exception to throw than an NPE?
👆 1
s

Shawn

04/30/2019, 6:56 PM
that’s really the crux of it, if you can’t proceed any further past that point if the value is null, throw an exception such that a human can understand what went wrong
c

Casey Brooks

04/30/2019, 6:57 PM
I’ve been growing fond of using the
check
or
checkNotNull
stdlib functions for this, to give some more info in stacktraces
site = checkNotNull(<http://dto.site|dto.site> ?: <http://this.site|this.site>) { "Site cannot be null" }
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/check-not-null.html
💯 2
k

kevinherron

04/30/2019, 6:58 PM
I like those where in Java I'd be using something like
Preconditions
from guava
s

streetsofboston

04/30/2019, 6:59 PM
Or, if 'null' is a proper and expected, but incorrect, input, you may want to properly model both good result and the possible errors. I would use something like an
Either<E,T>
as the type of this expression.
o

obobo

04/30/2019, 8:47 PM
you can do
?: error("Message describing what was expected")
too, if you don't mind throwing an IllegalStateException