Skip to content

Commit 94268a7

Browse files
committed
Update blog
1 parent 6792a0d commit 94268a7

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

content/Kotlin Contract.md

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
---
2+
title: Kotlin Contract
3+
description:
4+
aliases: []
5+
date: 2025-08-17
6+
tags: [Kotlin]
7+
comments: true
8+
---
9+
# Kotlin Contract
10+
## 배경
11+
```
12+
// 문자열이 유효한지 (null도 아니고 비어있지도 않은지) 검사하는 함수
13+
fun isValid(value: String?): Boolean {
14+
return value != null && value.isNotEmpty()
15+
}
16+
17+
fun printVerifiedLength(text: String?) {
18+
// isValid 함수로 text가 유효한지 검사
19+
if (isValid(text)) {
20+
// 컴파일 에러 발생
21+
// println(text.length)
22+
}
23+
}
24+
```
25+
- 컴파일러는 함수 내부까지 이해하지 않기 때문에, `isValid` 내부에서 value가 null-safe한지 모른다.
26+
- 그렇기 때문에 text.length를 호출하면, 컴파일러는 컴파일 에러를 반환하게 된다.
27+
- 이런 문제를 해결하기 위해 Kotlin Contract 탄생하게 되었다.
28+
29+
## How to use
30+
```
31+
fun isValid(value: String?): Boolean {
32+
contract {
33+
returns(true) implies (value != null)
34+
}
35+
return value != null && value.isNotEmpty()
36+
}
37+
```
38+
- 결과값을 true로 반환하면, value가 null이 아니라는 정보를 [[Compiler]]에게 전달한다.
39+
40+
## 쓰임새
41+
```
42+
fun runBlock(block: () -> Unit) {
43+
// '이 블록은 여기서, 정확히 한 번 실행된다'고 계약
44+
contract {
45+
callsInPlace(block,InvocationKind.EXACTLY_ONCE)
46+
}
47+
block()
48+
}
49+
```
50+
- 함수 호출 보증도 계약을 할 수 있다.
51+
52+
## Reference
53+
- https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.contracts/
54+
- https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.contracts/-contract-builder/
55+
- https://www.baeldung.com/kotlin/contracts

0 commit comments

Comments
 (0)