Skip to main content
InterviewHubPRO
Section Overview
Q49

Question 49 of 50

Part 3: K2 Compiler, KMP, Advanced Metaprogramming & Optimization (25 - 35)

98%
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-casts user to non-nullable User in subsequent lines!