Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of kotlin contract

Tags:

android

kotlin

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?

like image 396
Bachiri Taoufiq Abderrahman Avatar asked Mar 31 '20 19:03

Bachiri Taoufiq Abderrahman


Video Answer


1 Answers

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.

like image 69
Giorgio Antonioli Avatar answered Oct 22 '22 23:10

Giorgio Antonioli