未找到案例类值

时间:2017-04-14 12:35:26

标签: scala class case local

为什么要访问"数字匹配"告诉我没找到案例类? "未找到:值King"

class Field {
    val size: Int = StdIn.readInt()
    var matrix: List[List[Boolean]] = List.fill(size, size)(true)
    val figures: List[List[Figure]] = List()

    def inRange(figures: List[List[Figure]]) = {
        figures match {
            case King() => field.forEach(matrix) {
               if (matrix == true) {
                  if (Math.abs(m1-m2) <= 1 || Math.abs(n1-n2) <= 1) matrix = false
               }
            }
        }
    }

    abstract class Figure {
        case class Rook()
        case class Knight()
        case class Bishop()
        case class Queen()
        case class King()

    }

3 个答案:

答案 0 :(得分:1)

问题是King是在抽象类Figure中定义的。我想你要找的是继承。使用extends来实现:

abstract class Figure
case class Rook() extends Figure
case class Knight() extends Figure
case class Bishop() extends Figure
case class Queen() extends Figure
case class King() extends Figure

另外,如果你不需要任何关于Rook,Knight等的参数,我建议使用case object而不是case class

我希望这会对你有所帮助。

答案 1 :(得分:1)

King位于抽象类Figure中,在其外部不可见。

我想,你正在尝试做类似下面的事情

trait Figure

case class Rook() extends Figure
case class Knight() extends Figure
case class Bishop() extends Figure
case class Queen() extends Figure
case class King() extends Figure

现在RookKnight ...是数字,继承语义适用于它们。上面的代码称为声明代数数据类型。

现在给出一个类型为Figure的图形,你可以模式匹配并找到它的确切数字。

val figure: Figure = Rook()

figure match {
 case Rook() => "found Rook"
 case _ =>  "Not Rook"
}

以上代码现已生效。您的代码变为

abstract class Figure //Figure can be trait as well.

case class Rook() extends Figure
case class Knight() extends Figure
case class Bishop() extends Figure
case class Queen() extends Figure
case class King() extends Figure

根据您的目标

val listOfFigures: List[List[Figure]] = ....

listOfFigures.flatMap { figures =>
  figures.map { figure =>
   figure match {
     case Rook() => "Rook logic"
     case _ => "Some other logic"
   }
  }
}

答案 2 :(得分:1)

正如Pamu解释的那样,您希望将数字设置为代数数据类型。您可以将它们设置为案例对象而不是案例类,因为您没有任何属性:

def find_previous(List1, n):
    for i in range(len(List1)):
        if List1[i] == n and i > 0:
            return List1[i-1]
    return None

然后

trait Figure

case object Rook extends Figure
case object Knight extends Figure
case object Bishop extends Figure
case object Queen extends Figure
case object King extends Figure