Kotlin中的Contract契约是一种向编译器通知函数行为的方法。
起
代码语言:javascript复制 val nullList: List<Any>? = null
val b1 = nullList.isNullOrEmpty() // true
val empty: List<Any>? = emptyList<Any>()
val b2 = empty.isNullOrEmpty() // true
val collection: List<Char>? = listOf('a', 'b', 'c')
val b3 = collection.isNullOrEmpty() // false
另:
代码语言:javascript复制 fun f1(s: String?): Int {
return if (s != null) {
s.length
} else 0
}
it works, BUT :
代码语言:javascript复制fun f2(s: String?): Int {
return if (isNotEmpty(s)) {
s?.length ?: 0 // 我们需要使用 ?.
} else 0
}
fun isNotEmpty(s: String?): Boolean {
return s != null && s != ""
}
WHY ?
Contract 契约就是来解决这个问题的.
我们都知道Kotlin中有个非常nice的功能就是类型智能推导(官方称为smart cast), 不知道小伙伴们在使用Kotlin开发的过程中有没有遇到过这样的场景,会发现有时候智能推导能够正确识别出来,有时候却失败了。
承
代码语言:javascript复制/**
* Returns `true` if this nullable collection is either null or empty.
* @sample samples.collections.Collections.Collections.collectionIsNullOrEmpty
*/
@SinceKotlin("1.3")
@kotlin.internal.InlineOnly
public inline fun <T> Collection<T>?.isNullOrEmpty(): Boolean {
contract {
returns(false) implies (this@isNullOrEmpty != null)
}
return this == null || this.isEmpty()
}
so, what is contract ?
转
上面的这段代码说明:
inline fun <T> Collection<T>?.isNullOrEmpty(): Boolean
这个函数返回值如果是false, 那么 implies (this@isNullOrEmpty != null)
.
下面我们来探讨一下 contract 的语法:
contract 只能使用在 top level fun 中
使用ExperimentalContracts注解声明
由于Contract契约API (1.3中)还是Experimental,所以需要使用ExperimentalContracts注解声明.
contract should be the first statement
合
代码语言:javascript复制//由于Contract契约API还是Experimental,所以需要使用ExperimentalContracts注解声明
@ExperimentalContracts
fun isNotEmptyWithContract(s: String?): Boolean {
// val a = 1
// 这里契约的意思是: 调用 isNotEmptyWithContract 函数,会产生这样的效果: 如果返回值是true, 那就意味着 s != null. 把这个契约行为告知到给编译器,编译器就知道了下次碰到这种情形,你的 s 就是非空的,自然就smart cast了。
contract {
returns(true) implies (s != null)
}
return s != null && s != ""
}
fun f3(s: String?): Int {
return if (isNotEmptyWithContract(s)) {
s.length
} else 0
}
@ExperimentalContracts
fun main() {
val demo = ContractDemo()
demo.f3("abc")
}
再来一个稍微复杂一点的例子:
代码语言:javascript复制open class Animal(name: String)
fun Animal.isCat(): Boolean {
return this is Cat
}
class Cat : Animal("Cat") {
fun miao() {
println("MIAO~")
}
}
class Dog : Animal("Dog") {
fun wang() {
println("WANG~")
}
}
我们可以看到, 普通的 Animal.isCat()
编译器是无法自动推断出当前对象的类型的, 直接报错: Unresolved reference: miao .
只能类型强转: cat as Cat
.
fun Animal.isCat(): Boolean {
return this is Cat
}
这个时候 , 神奇的contract 魔法出现了:
代码语言:javascript复制@ExperimentalContracts
fun Animal.isDog(): Boolean {
contract {
returns(true) implies (this@isDog is Dog)
}
return this is Dog
}
我们可以看到, dog.wang()
可以直接调用了.
常见标准库函数run,also,with,apply,let
这些函数大家再熟悉不过吧,每个里面都用到contract契约:
代码语言:javascript复制//以apply函数举例,其他函数同理
@kotlin.internal.InlineOnly
public inline fun <T> T.apply(block: T.() -> Unit): T {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
block()
return this
}
契约解释: 看到这个契约是不是感觉一脸懵逼,不再是returns函数了,而是callsInPlace函数,还带传入一个InvocationKind.EXACTLY_ONCE参数又是什么呢? 该契约表示告诉编译器:调用apply函数后产生效果是指定block lamba表达式参数在适当的位置被调用。适当位置就是block lambda表达式只能在自己函数(这里就是指外层apply函数)被调用期间被调用,当apply函数被调用结束后,block表达式不能被执行,并且指定了InvocationKind.EXACTLY_ONCE表示block lambda表达式只能被调用一次,此外这个外层函数还必须是个inline内联函数。
Contract契约背后原理(Contract源码分析)
代码语言:javascript复制package kotlin.contracts
import kotlin.internal.ContractsDsl
import kotlin.internal.InlineOnly
/**
* This marker distinguishes the experimental contract declaration API and is used to opt-in for that feature
* when declaring contracts of user functions.
*
* Any usage of a declaration annotated with `@ExperimentalContracts` must be accepted either by
* annotating that usage with the [UseExperimental] annotation, e.g. `@UseExperimental(ExperimentalContracts::class)`,
* or by using the compiler argument `-Xuse-experimental=kotlin.contracts.ExperimentalContracts`.
*/
@Retention(AnnotationRetention.BINARY)
@SinceKotlin("1.3")
@Experimental
@MustBeDocumented
public annotation class ExperimentalContracts
/**
* Provides a scope, where the functions of the contract DSL, such as [returns], [callsInPlace], etc.,
* can be used to describe the contract of a function.
*
* This type is used as a receiver type of the lambda function passed to the [contract] function.
*
* @see contract
*/
@ContractsDsl
@ExperimentalContracts
@SinceKotlin("1.3")
public interface ContractBuilder {
/**
* Describes a situation when a function returns normally, without any exceptions thrown.
*
* Use [SimpleEffect.implies] function to describe a conditional effect that happens in such case.
*
*/
// @sample samples.contracts.returnsContract
@ContractsDsl public fun returns(): Returns
/**
* Describes a situation when a function returns normally with the specified return [value].
*
* The possible values of [value] are limited to `true`, `false` or `null`.
*
* Use [SimpleEffect.implies] function to describe a conditional effect that happens in such case.
*
*/
// @sample samples.contracts.returnsTrueContract
// @sample samples.contracts.returnsFalseContract
// @sample samples.contracts.returnsNullContract
@ContractsDsl public fun returns(value: Any?): Returns
/**
* Describes a situation when a function returns normally with any value that is not `null`.
*
* Use [SimpleEffect.implies] function to describe a conditional effect that happens in such case.
*
*/
// @sample samples.contracts.returnsNotNullContract
@ContractsDsl public fun returnsNotNull(): ReturnsNotNull
/**
* Specifies that the function parameter [lambda] is invoked in place.
*
* This contract specifies that:
* 1. the function [lambda] can only be invoked during the call of the owner function,
* and it won't be invoked after that owner function call is completed;
* 2. _(optionally)_ the function [lambda] is invoked the amount of times specified by the [kind] parameter,
* see the [InvocationKind] enum for possible values.
*
* A function declaring the `callsInPlace` effect must be _inline_.
*
*/
/* @sample samples.contracts.callsInPlaceAtMostOnceContract
* @sample samples.contracts.callsInPlaceAtLeastOnceContract
* @sample samples.contracts.callsInPlaceExactlyOnceContract
* @sample samples.contracts.callsInPlaceUnknownContract
*/
@ContractsDsl public fun <R> callsInPlace(lambda: Function<R>, kind: InvocationKind = InvocationKind.UNKNOWN): CallsInPlace
}
/**
* Specifies how many times a function invokes its function parameter in place.
*
* See [ContractBuilder.callsInPlace] for the details of the call-in-place function contract.
*/
@ContractsDsl
@ExperimentalContracts
@SinceKotlin("1.3")
public enum class InvocationKind {
/**
* A function parameter will be invoked one time or not invoked at all.
*/
// @sample samples.contracts.callsInPlaceAtMostOnceContract
@ContractsDsl AT_MOST_ONCE,
/**
* A function parameter will be invoked one or more times.
*
*/
// @sample samples.contracts.callsInPlaceAtLeastOnceContract
@ContractsDsl AT_LEAST_ONCE,
/**
* A function parameter will be invoked exactly one time.
*
*/
// @sample samples.contracts.callsInPlaceExactlyOnceContract
@ContractsDsl EXACTLY_ONCE,
/**
* A function parameter is called in place, but it's unknown how many times it can be called.
*
*/
// @sample samples.contracts.callsInPlaceUnknownContract
@ContractsDsl UNKNOWN
}
/**
* Specifies the contract of a function.
*
* The contract description must be at the beginning of a function and have at least one effect.
*
* Only the top-level functions can have a contract for now.
*
* @param builder the lambda where the contract of a function is described with the help of the [ContractBuilder] members.
*
*/
@ContractsDsl
@ExperimentalContracts
@InlineOnly
@SinceKotlin("1.3")
@Suppress("UNUSED_PARAMETER")
public inline fun contract(builder: ContractBuilder.() -> Unit) { }
源代码
https://github.com/EasyKotlin/kotlin-demo/blob/master/src/main/kotlin/com/light/sword/ContractDemo.kt
参考资料
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/is-null-or-empty.html
Kotlin 开发者社区
国内第一Kotlin 开发者社区公众号,主要分享、交流 Kotlin 编程语言、Spring Boot、Android、React.js/Node.js、函数式编程、编程思想等相关主题。
Kotlin 开发者社区