File tree Expand file tree Collapse file tree
core-kotlin/src/main/kotlin/com/baeldung/contract Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+
Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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>
You can’t perform that action at this time.
0 commit comments