Hey guys,
I am about to learn Kotlin (no computer science background) and just want to understand following code. Can somebody explain the following code and output to me (questions at the end)?
interface Expr
class Num(val value: Int): Expr
class Sum(val left: Expr, val right: Expr): Expr
fun main() {
fun evalWithLogging(e: Expr): Int =
when (e) {
is Sum -> {
val left = evalWithLogging(e.left)
val right = evalWithLogging(e.right)
println(“sum: $left + $right”)
// this is the last expression in the block and is returned if es is of type Sum
left + right
}
is Num -> {
println(“num: ${e.value}”)
// this is the last expression in the block and is returned if e is of type Num
e.value
}
else -> throw IllegalArgumentException(“Unknown Expression”)
}
println(evalWithLogging(Sum(Sum(Num(2), Num(1)), Num(4))))
}
The output is:
num: 2
num: 1
sum: 2 + 1
num: 4
sum: 3 + 4
7
Question1: Why is the sum of 2 + 1 not being returned?
Question2: The lines “e.value” and “left + right” are necessary since the “println” command is of type Unit and Int is expected?
Many thanks in advance!
submitted by /u/Marcel_Eff
[link] [comments]