Kotlin中的Contract契約是一種向編譯器通知函數(shù)行為的方法酱固。
起
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 契約就是來解決這個(gè)問題的.
我們都知道Kotlin中有個(gè)非常nice的功能就是類型智能推導(dǎo)(官方稱為smart cast), 不知道小伙伴們在使用Kotlin開發(fā)的過程中有沒有遇到過這樣的場景诅福,會(huì)發(fā)現(xiàn)有時(shí)候智能推導(dǎo)能夠正確識(shí)別出來恩敌,有時(shí)候卻失敗了县忌。
承
/**
* 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 ?
轉(zhuǎn)
上面的這段代碼說明:
inline fun <T> Collection<T>?.isNullOrEmpty(): Boolean
這個(gè)函數(shù)返回值如果是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
// 這里契約的意思是: 調(diào)用 isNotEmptyWithContract 函數(shù)败匹,會(huì)產(chǎn)生這樣的效果: 如果返回值是true, 那就意味著 s != null. 把這個(gè)契約行為告知到給編譯器寨昙,編譯器就知道了下次碰到這種情形,你的 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")
}
再來一個(gè)稍微復(fù)雜一點(diǎn)的例子:
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()
編譯器是無法自動(dòng)推斷出當(dāng)前對象的類型的, 直接報(bào)錯(cuò): Unresolved reference: miao .
只能類型強(qiáng)轉(zhuǎn): cat as Cat
.
fun Animal.isCat(): Boolean {
return this is Cat
}
這個(gè)時(shí)候 , 神奇的contract 魔法出現(xiàn)了:
@ExperimentalContracts
fun Animal.isDog(): Boolean {
contract {
returns(true) implies (this@isDog is Dog)
}
return this is Dog
}
我們可以看到, dog.wang()
可以直接調(diào)用了.
常見標(biāo)準(zhǔn)庫函數(shù)run,also,with,apply,let
這些函數(shù)大家再熟悉不過吧,每個(gè)里面都用到contract契約:
//以apply函數(shù)舉例槽棍,其他函數(shù)同理
@kotlin.internal.InlineOnly
public inline fun <T> T.apply(block: T.() -> Unit): T {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
block()
return this
}
契約解釋: 看到這個(gè)契約是不是感覺一臉懵逼捉蚤,不再是returns函數(shù)了,而是callsInPlace函數(shù)炼七,還帶傳入一個(gè)InvocationKind.EXACTLY_ONCE參數(shù)又是什么呢?
該契約表示告訴編譯器:調(diào)用apply函數(shù)后產(chǎn)生效果是指定block lamba表達(dá)式參數(shù)在適當(dāng)?shù)奈恢帽徽{(diào)用外里。適當(dāng)位置就是block lambda表達(dá)式只能在自己函數(shù)(這里就是指外層apply函數(shù))被調(diào)用期間被調(diào)用,當(dāng)apply函數(shù)被調(diào)用結(jié)束后特石,block表達(dá)式不能被執(zhí)行盅蝗,并且指定了InvocationKind.EXACTLY_ONCE表示block lambda表達(dá)式只能被調(diào)用一次,此外這個(gè)外層函數(shù)還必須是個(gè)inline內(nèi)聯(lián)函數(shù)姆蘸。
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://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/is-null-or-empty.html
Kotlin 開發(fā)者社區(qū)
國內(nèi)第一Kotlin 開發(fā)者社區(qū)公眾號(hào)墩莫,主要分享芙委、交流 Kotlin 編程語言、Spring Boot狂秦、Android灌侣、React.js/Node.js、函數(shù)式編程裂问、編程思想等相關(guān)主題侧啼。