- Learn Kotlin Programming(Second Edition)
- Stephen Samuel Stefan Bocutiu
- 161字
- 2021-06-24 14:13:31
Contracts API
Given the preceding code, let's put the new functionality to good use. All we need to do is annotate the validate method with @ExperimentalContracts and add the code at the beginning of the method body:
contract {
returns() implies (command != null)
}
The new code now looks like this:
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.contract
data class Command(val timestamp: Long)
@ExperimentalContracts
fun processCommand(command: Command?) {
validate(command)
println(command.timestamp)
}
@ExperimentalContracts
fun validate(command: Command?) {
contract {
returns() implies (command != null)
}
if (command == null) {
throw IllegalArgumentException("Invalid 'command' parameter. Expecting non-null parameter")
}
//... more validation here
}
With the changes in place, the compiler will not raise a compilation error anymore.
The general syntax for a code contract is as follows:
fun ... {
contract {
Effect
}
}
Effect is an interface that encapsulates the effect of invoking the function. It goes without saying, calling the function through reflection will not benefit from the Contracts API.