Kotlin & Coroutines (50 Qs)•Part 3: K2 Compiler, KMP, Advanced Metaprogramming & Optimization (25 - 35)
Contract DSL in Kotlin: Teaching the compiler custom smart-casting rules.
senior LevelCode ExamplePerformance
In Simple Words:
Custom helper functions (e.g. isNotNullOrEmpty()) usually defeat the compiler's native smart-casting. Contracts inform the compiler of custom guarantees:
kotlin
import kotlin.contracts.*
fun requireValidUser(user: User?) {
contract {
returns() implies (user != null)
}
if (user == null) throw IllegalArgumentException()
}
- After calling
requireValidUser(user), the compiler automatically smart-castsuserto non-nullableUserin subsequent lines!