Kotlin delegated property by map throwing NoSuchElementException if not present in map

You can basically use the .withDefault { ... } extension that wraps a Map for delegation, so that it executes the lambda to calculate a value on absent key:

data class UserUpdateRequest(val map: Map<String, Any?>) {
    private val defaultMap = map.withDefault { null }

    @get:Email
    val email: String? by defaultMap
    val firstName: String? by defaultMap
    val lastName: String? by defaultMap
}

Note that simple defaultMap.get(key) and defaultMap[key] queries are not handled by this wrapper, it only affects the defaulMap.getValue(key) calls (which also happen to be used by the delegation implementation).

Tags:

Kotlin