按字段解决案例

时间:2016-08-20 09:35:08

标签: scala

我有一个模拟国际象棋游戏的模块,有以下两个类:

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类型的变量?

1 个答案:

答案 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)