Scala 检查成员是否为零

Scala 检查成员是否为零,scala,Scala,假设我有一个树对象,它有两个成员对象,右和左 检查树的“right”和“left”字段是否为零的惯用/正确方法是什么 def count(tree: Tree, acc: Int) : Int = tree match { case tree .right != Nil && tree .left != Nil => countLeftAndRight(...) case tree .right != Nil => countOnlyRight(...)

假设我有一个
对象,它有两个成员对象,

检查
树的“right”和“left”字段是否为零的惯用/正确方法是什么

def count(tree: Tree, acc: Int) : Int = tree match {

  case tree .right != Nil && tree .left != Nil => countLeftAndRight(...)
  case tree .right != Nil => countOnlyRight(...)
  case tree .left  != Nil => countOnlyLeft(...)
  _              => acc
}

您的示例不是有效的Scala,但匹配树的惯用方法是使用提取器(查找)。如果
Tree
是一个case类,那么您可以免费获得它。假设是,你可以写

tree match {
  case Tree(Nil, Nil) => acc
  case Tree(Nil, x) => ...
  case Tree(x, Nil) => ...
  case Tree(x, y) => ...
}

您的示例不是有效的Scala,但匹配树的惯用方法是使用提取器(查找)。如果
Tree
是一个case类,那么您可以免费获得它。假设是,你可以写

tree match {
  case Tree(Nil, Nil) => acc
  case Tree(Nil, x) => ...
  case Tree(x, Nil) => ...
  case Tree(x, y) => ...
}

或者,如果您希望按原样使用非case类
,则可以尝试Luigi解决方案的以下变体:

(tree.left, tree.right) match {
  case (Nil, Nil) => acc
  case (Nil, x) => ...
  case (x, Nil) => ...
  case (x, y) => ...

或者,如果您希望按原样使用非case类
,则可以尝试Luigi解决方案的以下变体:

(tree.left, tree.right) match {
  case (Nil, Nil) => acc
  case (Nil, x) => ...
  case (x, Nil) => ...
  case (x, y) => ...

什么是
x
?您的匹配块似乎无效。抱歉-我更新为
,而不是
x
什么是
x
?您的匹配块似乎无效。抱歉-我更新为
,而不是
x
,case语句中的
x
y
是否指示
对象中的任何非
Nil
值?它们是将绑定到提取器返回的值的变量。(重要的是它们以小写字母开头。)这可以包括值
Nil
,这就是为什么我们首先匹配
Nil
,因此,以下情况是非Nil。case语句中的
x
y
是否表示
对象中的任何非
Nil
值?它们是绑定到提取器返回的值的变量。(重要的是它们以小写字母开头。)这可以包括值
Nil
,这就是为什么我们首先匹配
Nil
,因此以下情况是非Nil。