Merge pull request #5771 from denis-zhdanov/BAEL-2373-kotlin-contracts
BAEL-2373 Kotlin Contracts
This commit is contained in:
commit
cd873618a6
|
@ -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
|
||||||
|
}
|
||||||
|
|
|
@ -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
|
||||||
|
}
|
|
@ -202,7 +202,7 @@
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<kotlin.version>1.3.0</kotlin.version>
|
<kotlin.version>1.3.10</kotlin.version>
|
||||||
<kotlinx.version>1.0.0</kotlinx.version>
|
<kotlinx.version>1.0.0</kotlinx.version>
|
||||||
<ktor.io.version>0.9.5</ktor.io.version>
|
<ktor.io.version>0.9.5</ktor.io.version>
|
||||||
<assertj.version>3.11.0</assertj.version>
|
<assertj.version>3.11.0</assertj.version>
|
||||||
|
|
Loading…
Reference in New Issue