Skip to content

Null safety

A type can hold null only when it ends in ?. A plain String is never null.

var target: String? = null
target = "goblin"
val name: String = "Hans"

After != null, the value is used as the plain type.

val clan: String? = "Iron Wolves"
if (clan != null) {
Logger.info("Clan name has ${clan.length} letters.")
}

?. calls only when the value isn’t null, and gives null otherwise.

val clan: String? = null
val shout = clan?.uppercase()

?: gives a fallback when the left side is null.

val prices = mapOf("bread" to 4)
val price = prices["cake"] ?: 0

?: can return or throw instead of giving a value.

fun priceOf(item: String, prices: Map<String, Int>): Int {
val price = prices[item] ?: return 0
return price * 2
}
fun itemOrFail(item: String?): String = item ?: throw IllegalArgumentException("No item")

Inside a hook, ?: return@ and the hook’s name ends the block.

val titles = mapOf("Ana" to "the Brave")
on_login { player ->
val title = titles["Ana"] ?: return@on_login
player.message("Welcome, $title.")
}

?.let { } runs a block only when the value isn’t null. Inside, it is the value.

val clan: String? = "Iron Wolves"
clan?.let { Logger.info("Clan: $it") }

!! says a value is not null, and throws if it is. Prefer ?. and ?:.

val clan: String? = "Iron Wolves"
val sure: String = clan!!

as? gives null when the value isn’t that type.

val reward: Any = "dragon bones"
val coins = (reward as? Int) ?: 0

filterNotNull() drops the nulls. mapNotNull maps and drops in one step.

val slots = listOf("sword", null, "shield", null)
val held = slots.filterNotNull()
val lengths = slots.mapNotNull { it?.length }