Scala 摘要 类
Scala abstract classes
我正在学习 Coursera 的 Scala 课程,我遇到了抽象 classes 的一些问题。在这里,我试图从 CodeTree 摘要 class 的 case classes 访问字段,但编译器抱怨这些字段不属于 CodeTree class 本身。我认为模式匹配会解决这个问题,但显然不会。有帮助吗?
abstract class CodeTree
case class Fork(left: CodeTree, right: CodeTree, chars: List[Char], weight: Int) extends CodeTree
case class Leaf(char: Char, weight: Int) extends CodeTree
def weight(tree: CodeTree): Int = tree match {
case Leaf(_, weight) => tree.weight
case Fork(left, right, _, _) => weight(tree.left) + weight(tree.right)
}
编译器是对的,你的抽象class没有实例变量。
好消息是您不需要它们,您已经从 tree
输入参数的模式匹配中获得了所需的一切。
只需将您的代码修改为:
abstract class CodeTree
case class Fork(left: CodeTree, right: CodeTree, chars: List[Char], weight: Int) extends CodeTree
case class Leaf(char: Char, weight: Int) extends CodeTree
def weight(tree: CodeTree): Int = tree match {
case Leaf(_, weight) => weight
case Fork(left, right, _, _) => weight(left) + weight(right)
}
当您在 Scala 中成功进行模式匹配时,匹配子句左侧的变量可用于子句本身的右侧,因此:
- 在您的第一个子句中,您匹配了一个
Leaf
,因此您可以在右侧使用 weight
变量,它只是 returns it
- 在你的第二个子句中你匹配了一个
Fork
所以你有一个 left
和 right
变量可用于右侧(你丢弃 chars
和 weight
变量),递归调用weight
函数
您可以参考 Scala Tour 以更好地了解模式匹配的工作原理。
我正在学习 Coursera 的 Scala 课程,我遇到了抽象 classes 的一些问题。在这里,我试图从 CodeTree 摘要 class 的 case classes 访问字段,但编译器抱怨这些字段不属于 CodeTree class 本身。我认为模式匹配会解决这个问题,但显然不会。有帮助吗?
abstract class CodeTree
case class Fork(left: CodeTree, right: CodeTree, chars: List[Char], weight: Int) extends CodeTree
case class Leaf(char: Char, weight: Int) extends CodeTree
def weight(tree: CodeTree): Int = tree match {
case Leaf(_, weight) => tree.weight
case Fork(left, right, _, _) => weight(tree.left) + weight(tree.right)
}
编译器是对的,你的抽象class没有实例变量。
好消息是您不需要它们,您已经从 tree
输入参数的模式匹配中获得了所需的一切。
只需将您的代码修改为:
abstract class CodeTree
case class Fork(left: CodeTree, right: CodeTree, chars: List[Char], weight: Int) extends CodeTree
case class Leaf(char: Char, weight: Int) extends CodeTree
def weight(tree: CodeTree): Int = tree match {
case Leaf(_, weight) => weight
case Fork(left, right, _, _) => weight(left) + weight(right)
}
当您在 Scala 中成功进行模式匹配时,匹配子句左侧的变量可用于子句本身的右侧,因此:
- 在您的第一个子句中,您匹配了一个
Leaf
,因此您可以在右侧使用weight
变量,它只是 returns it - 在你的第二个子句中你匹配了一个
Fork
所以你有一个left
和right
变量可用于右侧(你丢弃chars
和weight
变量),递归调用weight
函数
您可以参考 Scala Tour 以更好地了解模式匹配的工作原理。