当前位置:网站首页>Can't understand kotlin source code? Starting with the contracts function~
Can't understand kotlin source code? Starting with the contracts function~
2022-06-12 18:53:00 【Huanglinqing】
Preface
Recently, a friend reported that the source code is Kotlin, So I can't understand . Actually , Sometimes I can't understand Kotlin Probably because you don't know some specific syntax . Just as you don't understand the source code because you don't understand the design pattern ~
for instance
With Kotlin Commonly used isNullOrEmpty Methods as an example , The source code is shown below :
@kotlin.internal.InlineOnly
public inline fun CharSequence?.isNullOrEmpty(): Boolean {
contract {
returns(false) implies ([email protected] != null)
}
return this == null || this.length == 0
}Why ? The code is simple , But I can't understand it ?contract What the hell is it ,implies What the hell is it ? In fact, when you understand contract After the use of the function , You can understand similar source code .
Contracts What is it? ?
Contracts It's a contract 、 Meaning of contract . from Kotlin1.3 Version was introduced , In a nutshell Contracts It can be used to solve some functions that the compiler cannot complete .
therefore , What on earth does it do ?
Let's define a similar function , Used to detect whether an object is null, So let's define a User object , The code is as follows :
data class User(val name: String, val age: Int)Define another check User Whether the object is empty , The code is as follows :
fun isEmpty(user: User?) {
if (user == null) {
throw IllegalArgumentException("is empty")
}
}Then we call... In the business method , The code is as follows :
fun work(user: User?){
isEmpty(user = user)
setText(user.name)
}At this point, this method cannot be compiled , The compiler will remind you of user Is a nullable object , Need to add "?.",
But from our code logic , We first call isEmpty Method , If user The object is null Words , It's in isEmpty An exception has been thrown in the method , That is to say, it will not go to setText In the method . let me put it another way , If the code can be executed to setText In this business user The object must not be empty . So what to do now ? This requires Contracts Appearance. .
Contracts How to use
Contracts API It is generally shown as follows :
fun A() {
contract {
}
}At present, the main methods of use are returns、callsInPlace etc. , First let's look at returns Usage scenarios of .
Returns Contracts
contract {
returns($value) implies($condition)
}returns Used to tell the editor when the return value is value when condition Conditions established . At present value It can be Boolean or empty ,condition Conditional expressions also need to return Boolean types .
such as , Let's revise it now isEmpty Method , The code is as follows :
@ExperimentalContracts
fun isEmpty(user: User?) {
contract {
returns() implies (user != null)
}
if (user == null) {
throw IllegalArgumentException("is empty")
}
}Here we go through contract Constraints tell the compiler , If isEmpty Function can return normally , It means that user Not empty . In other words, understand , That is to say, when user When it is empty, an exception is thrown , therefore isEmpty Function cannot return .
You'll find that , When it changes isEmpty After method ,work Methods no longer report errors .
This is because we have passed isEmpty Method tells the compiler , If code can be executed to setText, explain user The object must not be empty . Because this function is always experimental API, So add here @ExperimentalContracts annotation .
however , at present Kotlin This has been used in many source codes API, So we don't have to worry about big changes in the future . And then we'll see CallInPlace Usage scenarios of .
CallInPlace Contracts
CallInPlace Is also widely used , Let's say we have Kotlin Standard functions commonly used in apply、also etc. . Here we use apply Function as an example ,apply The source code of the function is as follows :
@kotlin.internal.InlineOnly
public inline fun <T> T.apply(block: T.() -> Unit): T {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
block()
return this
}We can see from the source code that , It's used inside callsInPlace Method .callsInPlace You can tell the editor block Method is executed only once . instead of 0 Times or times . Of course, you can also set the method to execute at least once or at most once . This reader can try for himself .
Contracts Source code
So let's look at this first contract Source code of function , As shown below :
@ContractsDsl
@ExperimentalContracts
@InlineOnly
@SinceKotlin("1.3")
@Suppress("UNUSED_PARAMETER")
public inline fun contract(builder: ContractBuilder.() -> Unit) { }contract It's an inline function , Need one ContractBuilder object , Then look ContractBuilder Object source code , As shown below :
@ContractsDsl
@ExperimentalContracts
@SinceKotlin("1.3")
public interface ContractBuilder {
@ContractsDsl public fun returns(): Returns
@ContractsDsl public fun returns(value: Any?): Returns
@ContractsDsl public fun returnsNotNull(): ReturnsNotNull
@ContractsDsl public fun <R> callsInPlace(lambda: Function<R>, kind: InvocationKind = InvocationKind.UNKNOWN): CallsInPlace
}We can see returns Method returns Returns,callsInPlace Method returns CallsInPlace, and Returns The object is SimpleEffect The interface implements the self interface Effect,CallsInPalce The object is Effect Interface , The source code is shown below :
@ContractsDsl
@ExperimentalContracts
@SinceKotlin("1.3")
public interface SimpleEffect : Effect {
@ContractsDsl
@ExperimentalContracts
public infix fun implies(booleanExpression: Boolean): ConditionalEffect
}
@ContractsDsl
@ExperimentalContracts
@SinceKotlin("1.3")
public interface CallsInPlace : Effectfrom SimpleEffect You can see in the source code , It implements a infix function named implies, To tell the compiler booleanExpression To be established , So as to agree with the compiler .
At the end
contract In fact, it is through an agreement with the compiler , It makes up for the shortcomings of intelligent transformation .
Some things may happen in the near future , To borrow “ Heart theory ” What the boss said today is —— 2022 year , It's a good thing ~
边栏推荐
- kali通过iptables实现端口转发功能
- Difference between rxjs of() and of ({})
- RHCA回忆录---CL280介绍
- 【图像去噪】基于正则化实现图像去噪附matlab代码
- 笔记本电脑清灰打硅脂后,开机一直黑屏,如何破?
- 从应无所住说起
- [today in history] June 12: the United States entered the era of digital television; Mozilla's original developer was born; 3com merges with American Robotics
- tarfile解压嵌套tar
- 机器学习在美团配送系统的实践:用技术还原真实世界-笔记
- 2022.6.12-----leetcode.890
猜你喜欢
![Two months later, my second listing anniversary [June 2, 2022]](/img/55/6678659a552ba7dbace330d8b9c3ae.png)
Two months later, my second listing anniversary [June 2, 2022]
![leetcode:6094. Company name [group enumeration + cannot repeat set intersection + product Cartesian product (repeat indicates length)]](/img/6c/f42bbec7ff2ec0d104f1dd2c97eab6.png)
leetcode:6094. Company name [group enumeration + cannot repeat set intersection + product Cartesian product (repeat indicates length)]
![[today in history] June 12: the United States entered the era of digital television; Mozilla's original developer was born; 3com merges with American Robotics](/img/91/d7d6137b95f6348f71692164614340.png)
[today in history] June 12: the United States entered the era of digital television; Mozilla's original developer was born; 3com merges with American Robotics

Redis中的事务

Liunx deploy Seata (Nacos version)

国内如何下载ProxyStrike

【矩阵论 & 图论】期末考试复习思维导图

Chrome browser solves cross domain problems
![leetcode:5259. Calculate the total tax payable [simple simulation + see which range]](/img/f4/e6329c297dbe668e70f5e37bfc2852.png)
leetcode:5259. Calculate the total tax payable [simple simulation + see which range]

吃饭咯 干锅肥肠 + 掌中宝!
随机推荐
SCI Writing - Results
从应无所住说起
leetcode:6096. Success logarithm of spells and potions [sort + dichotomy]
Review of MySQL (IX): index
JS get the start and end dates of this week according to the nth week of the N year
leetcode:6096. 咒语和药水的成功对数【排序 + 二分】
六石认知学:大脑的显速与潜速
ISCC2022
Review of MySQL (V): Joint table query and sub query
Hugo blog building tutorial
2022.6.12-----leetcode. eight hundred and ninety
CVPR 2022 oral Dalian Institute of technology proposed SCI: a fast and powerful low light image enhancement method
SCI Writing - Methodology
Six stone cognition: the apparent and potential speed of the brain
dumi 搭建文档型博客
Have a meal, dry pot, fat intestines + palm treasure!
【图像去噪】基于各向异性滤波实现图像去噪附matlab代码
no available service ‘null‘ found, please make sure registry config correct
Istio 1.14 发布
Leetcode topic [string]-541- reverse string II