Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...