if 와 when Kotlin


interface Expr // open class Expr
class Num(val value: Int) : Expr
class Sum(val left: Expr, val right: Expr) : Expr

fun eval(e: Expr): Int =
if (e is Num) {
e.value
} else if (e is Sum) {
eval(e.right) + eval(e.left)
} else {
throw IllegalArgumentException("Unknown expression")
}

fun eval_when(e: Expr): Int =
when (e) {
is Num -> e.value
is Sum -> eval(e.right) + eval(e.left)
else -> throw IllegalArgumentException("Unknown expression")
}

fun eval_log(e: Expr): Int =
when (e) {
is Num -> {
println("num: ${e.value}")
e.value
}
is Sum -> {
val left = eval_log(e.left)
val right = eval_log(e.right)
println("sum: $left + $right")
left + right
}
else -> {
throw IllegalArgumentException("Unknown expression")
}
}

덧글

댓글 입력 영역