Skip to content

Preconditions

MerlinTHS edited this page Feb 16, 2023 · 1 revision

Use ensure to check conditions. It's internal use of Kotlin Contracts makes IntelliJ aware of your contract and results in a better IDE assistance.

Given a nullable property 1. Instead of declaring a new property, that's delegated by validation 2. You can use ensure to treat the old one as a non-nullable type 3.

// Nullable Property (1)
val maybeName: String? = "Peter"

// Delegated Validation (2)
val name by maybeName

// Ensured Conditions (3)
ensure (maybeName != null)

Or use the trailing lambda syntax to combine multiple conditions for the same receiver.

ensure (name) {
    isNotBlank() and (length > 2)
}

You can also use fail in combination with if, when or the Elvis Operator ?: as more flexible alternatives.

ensure is written in the same coding style as if - statements are, because the usage is conceptually quite the same. Statements below it will only be executed, if the condition is true.

List - Notation

To shorten precondition checks, you can replace ensure with a special overloaded unaryPlus operator in the context of a ValidationScope. It looks more like listing all the preconditions, than ensuring them step by step.

fun save(
    name: String,
    description: String
) = validate {
    + name { isNotBlank() }
    + description { length > 20 }
    
    // ...
}

Clone this wiki locally