dumptruckman
03/26/2020, 8:36 PMtddmonkey
03/26/2020, 8:38 PM?: error("some useful information about why it failed")
Shawn
03/26/2020, 8:38 PMShawn
03/26/2020, 8:38 PMShawn
03/26/2020, 8:39 PMerror()
with a useful message is way more helpful (and easier to search for in the codebase)dumptruckman
03/26/2020, 8:42 PMtddmonkey
03/26/2020, 8:43 PM!!
is when it absolutely cannot be null but I’m interoping with something that doesn’t let the compiler knowdumptruckman
03/26/2020, 8:51 PMval timestamp: LocalDate = rs["create_date"]!!
dumptruckman
03/26/2020, 8:51 PMdumptruckman
03/26/2020, 8:52 PMShawn
03/26/2020, 8:54 PMdumptruckman
03/26/2020, 8:54 PMinline operator fun <reified T> ResultSet.get(columnLabel: CharSequence): T? = getObject(columnLabel.toString(), T::class.java)
dumptruckman
03/26/2020, 8:54 PMT
right?Shawn
03/26/2020, 8:55 PMdumptruckman
03/26/2020, 8:55 PMdumptruckman
03/26/2020, 8:58 PMdumptruckman
03/26/2020, 9:00 PMdumptruckman
03/26/2020, 9:01 PMint
and easily use rs["id"] ?: 0
dumptruckman
03/26/2020, 9:04 PMdumptruckman
03/26/2020, 9:05 PMMessage(
rs["create_date"] ?: error("create_date is null"),
rs["body"] ?: error("body is null"),
rs["subject"],
rs["message_id"] ?: error("message_id is null")
)
dumptruckman
03/26/2020, 9:06 PMShawn
03/26/2020, 9:07 PMdumptruckman
03/26/2020, 9:07 PMShawn
03/26/2020, 9:08 PMget()
and a getNullable()
Shawn
03/26/2020, 9:09 PMgetThrowing()
if you actually want that to be the exceptional behaviorShawn
03/26/2020, 9:09 PMdumptruckman
03/26/2020, 9:10 PMMessage(
rs["create_date"]!!,
rs["body"]!!,
rs["subject"],
rs["message_id"]!!
)
Shawn
03/26/2020, 9:12 PMMessage(
rs["create_date"], // these will throw
rs["body"],
rs.getNullable("subject"), // this will not
rs["message_id"]
)
it’s perhaps not as nice-looking but is probably easier to debugShawn
03/26/2020, 9:12 PMShawn
03/26/2020, 9:12 PMdumptruckman
03/26/2020, 9:13 PMinvoke
operator for the other case… but that’s probably not a good idea.Shawn
03/26/2020, 9:14 PMdumptruckman
03/26/2020, 9:15 PMdumptruckman
03/26/2020, 9:22 PMrs["id"] { 0 }
dumptruckman
03/26/2020, 9:22 PMdumptruckman
03/26/2020, 9:23 PMShawn
03/26/2020, 9:23 PMdumptruckman
03/26/2020, 9:23 PMT?
it would still NPE if the result of getObject
ended up being nulldumptruckman
03/26/2020, 9:24 PMsindrenm
03/27/2020, 9:26 AM?: error("message")
approach, there's also checkNotNull
and requireNotNull
, which might be of interest. I tend to favor those over !!
, at least, and usually also checkNotNull(foo) { "message" }
over foo ?: error("message")
.tddmonkey
03/27/2020, 9:59 AMMessage(
rs["create_date"].orDie(),
rs["body"].orDie(),
rs["subject"],
rs["message_id"].orDie()
)
Mike
03/27/2020, 1:02 PMcheckNull
or requireNull
calls. And function returns non-null. More explicit than !!, and throws Illegal
exception rather than NPE.
I find that more realistic, as !!
should only be used in cases where the compiler can't figure it out, but you KNOW it can't/won't be null at that point.