Null safety
Nullable types
Section titled “Nullable types”A type can hold null only when it ends in ?. A plain String is never null.
var target: String? = nulltarget = "goblin"
val name: String = "Hans"Checking for null
Section titled “Checking for null”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.")}Safe calls
Section titled “Safe calls”?. calls only when the value isn’t null, and gives null otherwise.
val clan: String? = null
val shout = clan?.uppercase()The Elvis operator
Section titled “The Elvis operator”?: gives a fallback when the left side is null.
val prices = mapOf("bread" to 4)
val price = prices["cake"] ?: 0Leaving early
Section titled “Leaving early”?: 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")Leaving a hook early
Section titled “Leaving a hook early”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") }Not-null assertion
Section titled “Not-null assertion”!! says a value is not null, and throws if it is. Prefer ?. and ?:.
val clan: String? = "Iron Wolves"
val sure: String = clan!!Safe casts
Section titled “Safe casts”as? gives null when the value isn’t that type.
val reward: Any = "dragon bones"
val coins = (reward as? Int) ?: 0Collections of nullable values
Section titled “Collections of nullable values”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 }