Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

android - What is the purpose of kotlin contract

Was reading the apply function code source and found

contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }

and contract has an empty body, experimental

@ContractsDsl
@ExperimentalContracts
@InlineOnly
@SinceKotlin("1.3")
@Suppress("UNUSED_PARAMETER")
public inline fun contract(builder: ContractBuilder.() -> Unit) { }

what is the real purpose of contract and is it here to stay in the next versions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What is the real purpose of contract

The real purpose of Kotlin contracts is to help the compiler to make some assumptions which can't be made by itself. Sometimes the developer knows more than the compiler about the usage of a certain feature and that particular usage can be taught to the compiler.

I'll make an example with callsInPlace since you mentioned it.

Imagine to have the following function:

fun executeOnce(block: () -> Unit) {
  block()
}

And invoke it in this way:

fun caller() {
  val value: String 
  executeOnce {
      // It doesn't compile since the compiler doesn't know that the lambda 
      // will be executed once and the reassignment of a val is forbidden.
      value = "dummy-string"
  }
}

Here Kotlin contracts come in help. You can use callsInPlace to teach the compiler about how many times that lambda will be invoked.

@OptIn(ExperimentalContracts::class)
fun executeOnce(block: ()-> Unit) {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    block()
}

@OptIn(ExperimentalContracts::class)
fun caller() {
  val value: String 
  executeOnce {
      // Compiles since the val will be assigned once.
      value = "dummy-string"
  }
}

is it here to stay in the next versions?

Who knows. They are still experimental after one year, which is normal for a major feature. You can't be 100% sure they will be out of experimental, but since they are useful and they are here since one year, in my opinion, likely they'll go out of experimental.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...