So one of the kotlin koans is about using safe cas...
# getting-started
m
So one of the kotlin koans is about using safe casts. For example:
Copy code
fun 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)
t
disclaimer, I did not do the koans, but isn't
eval
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?
the point of this exercise is to show you that once the check for type is successful, in kotlin you don't actually need to store in an intermediate "casted" variable. like as if in Java you would be able to write
Copy code
if (obj instanceof String) {
  obj.concat("1");
}
k
Can you link to the Kotlin docs that say not to use
eval
?
m
I'm suspecting the "don't use eval" sentence is about the Javascript eval function.
👍 1
✔️ 1
💯 1
m
It was. I’m an idiot. I didn’t realize it was a recurive method. The “eval” is a call back on itself. Until it works down to the base class (Int). I got thrown by “eval” thinking it was a kotlin function (which there is one, just not this one). My fault. Thanks…