《Kotlin Contract 契约》极简教程

Kotlin中的Contract契约是一种向编译器通知函数行为的方法。

    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

另:

    fun f1(s: String?): Int {
        return if (s != null) {
            s.length
        } else 0
    }

it works, BUT :


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开发的过程中有没有遇到过这样的场景,会发现有时候智能推导能够正确识别出来,有时候却失败了。

/**
 * 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

//由于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")
}

再来一个稍微复杂一点的例子:

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 魔法出现了:

@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契约:

//以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源码分析)

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 开发者社区
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,496评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,407评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,632评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,180评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,198评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,165评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,052评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,910评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,324评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,542评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,711评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,424评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,017评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,668评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,823评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,722评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,611评论 2 353