我有一个模拟国际象棋游戏的模块,有以下两个类:
case class Pos(x: Char, y: Char)
abstract class Piece(player: Int, pos: Pos)
我有一套Piece
:
val pieces: Set[Piece]
我想像这样过滤它:
pieces.filter(piece => !(piece.pos == pos2))
但是,我收到此错误:
Error:(45, 36) value pos is not a member of chess.Piece
pieces.filter(piece => !(piece.pos == pos2))
^
为什么会这样?我是否可以使用Piece
引用.pos
类型的变量?
答案 0 :(得分:2)
这是因为没有为你的Piece类设置getter。
// No getters/setters created
abstract class Piece(player: Int, pos: Pos)
// Only Getters created because constructor params are immutable
abstract class Piece(val player: Int, val pos: Pos)
// Both Getters & Setter created because constructor params are mutable
abstract class Piece(var player: Int, var pos: Pos)