Merge pull request #5771 from denis-zhdanov/BAEL-2373-kotlin-contracts

BAEL-2373 Kotlin Contracts
This commit is contained in:
Loredana Crusoveanu 2018-12-20 22:46:08 +02:00 committed by GitHub
commit cd873618a6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 67 additions and 1 deletions

View File

@ -0,0 +1,23 @@
package com.baeldung.contract
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
@ExperimentalContracts
inline fun <R> myRun(block: () -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return block()
}
@ExperimentalContracts
fun callsInPlace() {
val i: Int
myRun {
i = 1 // Without contract initialization is forbidden due to possible re-assignment
}
println(i) // Without contract variable might be uninitialized
}

View File

@ -0,0 +1,43 @@
package com.baeldung.contract
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.contract
data class Request(val arg: String)
class Service {
@ExperimentalContracts
fun process(request: Request?) {
validate(request)
println(request.arg)
}
}
@ExperimentalContracts
private fun validate(request: Request?) {
contract {
returns() implies (request != null)
}
if (request == null) {
throw IllegalArgumentException("Undefined request")
}
}
data class MyEvent(val message: String)
@ExperimentalContracts
fun processEvent(event: Any?) {
if (isInterested(event)) {
println(event.message) // Compiler makes smart cast here with the help of contract
}
}
@ExperimentalContracts
fun isInterested(event: Any?): Boolean {
contract {
returns(true) implies (event is MyEvent)
}
return event is MyEvent
}

View File

@ -202,7 +202,7 @@
</build>
<properties>
<kotlin.version>1.3.0</kotlin.version>
<kotlin.version>1.3.10</kotlin.version>
<kotlinx.version>1.0.0</kotlinx.version>
<ktor.io.version>0.9.5</ktor.io.version>
<assertj.version>3.11.0</assertj.version>