KOTLIN · 함수형
Either/Result 타입
Either 타입으로 성공과 실패를 명시적으로 표현합니다. 예외 대신 반환값으로 에러를 처리하는 함수형 패턴입니다.
함수형고급eitherresultfunctional-errorfold
핵심 설명
Either 타입으로 성공과 실패를 명시적으로 표현합니다. 예외 대신 반환값으로 에러를 처리하는 함수형 패턴입니다.
Kotlin code
sealed class Either<out L, out R> {
data class Left<L>(val value: L) : Either<L, Nothing>()
data class Right<R>(val value: R) : Either<Nothing, R>()
fun <T> fold(onLeft: (L) -> T, onRight: (R) -> T): T = when (this) {
is Left -> onLeft(value)
is Right -> onRight(value)
}
fun <T> map(f: (R) -> T): Either<L, T> = when (this) {
is Left -> this
is Right -> Right(f(value))
}
fun <T> flatMap(f: (R) -> Either<L, T>): Either<L, T> = when (this) {
is Left -> this
is Right -> f(value)
}
}
fun parseInt(s: String): Either<String, Int> =
s.toIntOrNull()?.let { Either.Right(it) }
?: Either.Left("'$s'는 숫자가 아닙니다")
fun divide(a: Int, b: Int): Either<String, Double> =
if (b == 0) Either.Left("0으로 나눌 수 없습니다")
else Either.Right(a.toDouble() / b)
fun main() {
val result = parseInt("10")
.flatMap { n -> divide(n, 3) }
.map { "결과: %.2f".format(it) }
result.fold(
onLeft = { println("오류: $it") },
onRight = { println(it) }
)
}학습 팁
관례적으로 Left는 에러, Right는 성공을 나타냅니다. "Right is right(올바른)"으로 기억하세요.
주의할 점
flatMap 체인에서 첫 번째 Left가 발생하면 나머지 연산이 모두 건너뛰어집니다. 이를 의도적으로 활용하세요.
자주 묻는 질문
Either/Result 타입란 무엇인가요?
Either 타입으로 성공과 실패를 명시적으로 표현합니다. 예외 대신 반환값으로 에러를 처리하는 함수형 패턴입니다.
Either/Result 타입 학습 시 주의할 점은 무엇인가요?
flatMap 체인에서 첫 번째 Left 가 발생하면 나머지 연산이 모두 건너뛰어집니다. 이를 의도적으로 활용하세요.
Continue Learning
Kotlin 학습을 이어가세요
총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.