-
Notifications
You must be signed in to change notification settings - Fork 0
Preconditions
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.
ensureis written in the same coding style asif- statements are, because the usage is conceptually quite the same. Statements below it will only be executed, if the condition istrue.
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 }
// ...
}