使用 class 的属性而不必每次都写下它的名字
Using a class's properties without having to write its name down every time
fun eval(expr: Expr): Int =
when (expr) {
is Num -> expr.value
is Sum -> expr.left + expr.right
}
interface Expr
class Num(val value: Int) : Expr
class Sum(val left: Expr, val right: Expr) : Expr
我想理想地使用 value
、left
和 right
,而不必每次都调用 expr
。这可能吗?
这就是 with
作用域函数的用途。
fun eval(expr: Expr): Int = with (expr) {
when (this) {
is Num -> value
is Sum -> left + right
}
}
fun eval(expr: Expr): Int =
when (expr) {
is Num -> expr.value
is Sum -> expr.left + expr.right
}
interface Expr
class Num(val value: Int) : Expr
class Sum(val left: Expr, val right: Expr) : Expr
我想理想地使用 value
、left
和 right
,而不必每次都调用 expr
。这可能吗?
这就是 with
作用域函数的用途。
fun eval(expr: Expr): Int = with (expr) {
when (this) {
is Num -> value
is Sum -> left + right
}
}