Mike
05/16/2019, 12:51 PMfun eval(expr: Expr): Int =
when (expr) {
is Num -> expr.value
is Sum -> eval(expr.left) + eval(expr.right)
else -> throw IllegalArgumentException("Unknown expression")
}
interface Expr
class Num(val value: Int) : Expr
class Sum(val left: Expr, val right: Expr) : Expr
What I don’t understand is the use of the “eval” . If you go look at the kotlin docs they say “don’t use! Really Bad!” And it seems like you would want to do something like expr.left.value + expr.right.value. But it doesn’t know if left and right are Expr or Num. So you should be able to explicitly cast, but then you have to check to make sure it is the right type. It gets very messy very quick. Am I missing something? Or is this really just a made up example and in real-life we’d never do something like this. If I was doing this pattern in real code, I don’t think I’d use the data class / interface this way. I’d be able to get the classes to evaluate down to a value on their own, but then I wouldn’t need to worry about downcasting then (which defeats the point of the exercise)thanksforallthefish
05/16/2019, 12:55 PMeval
just a recursive call in this example? Aren't you confusing this eval
(which is just the name of the function) with some built-in kotlin function?if (obj instanceof String) {
obj.concat("1");
}
karelpeeters
05/16/2019, 1:00 PMeval
?marstran
05/16/2019, 1:01 PMMike
05/18/2019, 2:33 AM