Skip to content

Commit 0d5d303

Browse files
committed
BAEL-2373 Kotlin Contracts
* upgraded kotlin version to 1.3.10 * added contract examples
1 parent cfd9a97 commit 0d5d303

3 files changed

Lines changed: 67 additions & 1 deletion

File tree

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package com.baeldung.contract
2+
3+
import kotlin.contracts.ExperimentalContracts
4+
import kotlin.contracts.InvocationKind
5+
import kotlin.contracts.contract
6+
7+
@ExperimentalContracts
8+
inline fun <R> myRun(block: () -> R): R {
9+
contract {
10+
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
11+
}
12+
return block()
13+
}
14+
15+
@ExperimentalContracts
16+
fun callsInPlace() {
17+
val i: Int
18+
myRun {
19+
i = 1 // Without contract initialization is forbidden due to possible re-assignment
20+
}
21+
println(i) // Without contract variable might be uninitialized
22+
}
23+
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package com.baeldung.contract
2+
3+
import kotlin.contracts.ExperimentalContracts
4+
import kotlin.contracts.contract
5+
6+
data class Request(val arg: String)
7+
8+
class Service {
9+
10+
@ExperimentalContracts
11+
fun process(request: Request?) {
12+
validate(request)
13+
println(request.arg)
14+
}
15+
16+
}
17+
18+
@ExperimentalContracts
19+
private fun validate(request: Request?) {
20+
contract {
21+
returns() implies (request != null)
22+
}
23+
if (request == null) {
24+
throw IllegalArgumentException("Undefined request")
25+
}
26+
}
27+
28+
data class MyEvent(val message: String)
29+
30+
@ExperimentalContracts
31+
fun processEvent(event: Any?) {
32+
if (isInterested(event)) {
33+
println(event.message) // Compiler makes smart cast here with the help of contract
34+
}
35+
}
36+
37+
@ExperimentalContracts
38+
fun isInterested(event: Any?): Boolean {
39+
contract {
40+
returns(true) implies (event is MyEvent)
41+
}
42+
return event is MyEvent
43+
}

‎parent-kotlin/pom.xml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -202,7 +202,7 @@
202202
</build>
203203

204204
<properties>
205-
<kotlin.version>1.3.0</kotlin.version>
205+
<kotlin.version>1.3.10</kotlin.version>
206206
<kotlinx.version>1.0.0</kotlinx.version>
207207
<ktor.io.version>0.9.5</ktor.io.version>
208208
<assertj.version>3.11.0</assertj.version>

0 commit comments

Comments
 (0)