BAEL-2373 Kotlin Contracts

* upgraded kotlin version to 1.3.10
* added contract examples
This commit is contained in:
Denis Zhdanov 2018-11-25 13:53:48 +08:00
parent cfd9a97bd4
commit 0d5d3039cf
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>