rharriso
rharriso

Reputation: 1171

Can the Kotlin Compiler Require non-null assertion?

Can the Kotlin Compiler require non-null assertions?

for example. I'm getting a query result from JOOQ, and the relting type is Record!. But the compiler allows me to access members without checking for null.

val orderResult = RowanDatabaseConnector.runInContext(DatabaseContext.BOOKSTORE) {
    it.select(SPREE_ORDERS.asterisk())
        .from(SPREE_ORDERS)
        .where(SPREE_ORDERS.ID.eq(orderId.toInt()))
        .fetchOne()
}

return Cart(
    user = currentUser,
    subTotal = orderResult.get(SPREE_ORDERS.ITEM_TOTAL).toFloat(),
    taxTotal = orderResult.get(SPREE_ORDERS.ADDITIONAL_TAX_TOTAL).toFloat(),
    total = orderResult.get(SPREE_ORDERS.TOTAL).toFloat(),
    lineItems = listOf()
)        

Is there something similar to Typescript's strictNullCheck that would require that I assert that orderResult is not null?

Upvotes: 0

Views: 73

Answers (1)

Ben P.
Ben P.

Reputation: 54194

For platform types (any type ending with !), you can use an explicit type specification to declare whether it is supposed to be nullable or not.

If you want to make it explict that orderResult might be null, then you could write it like this:

val orderResult: Record? = /* trimmed */

Conversely, if you want to make it explicit that orderResult can't possibly be null, then you could write:

val orderResult: Record = /* trimmed *

By choosing one of these two options, the type will be Record? or Record instead of Record!. And, as such, you will get the null safety you're used to from Kotlin.

Upvotes: 2

Related Questions