octavian octavian - 3 months ago 12
Scala Question

Address case class by field

I have a module which simulates the game of chess, with the following two classes:

case class Pos(x: Char, y: Char)
abstract class Piece(player: Int, pos: Pos)


I have a set of
Piece
:

val pieces: Set[Piece]


I would like to filter it like this:

pieces.filter(piece => !(piece.pos == pos2))


However, I am getting this error:

Error:(45, 36) value pos is not a member of chess.Piece
pieces.filter(piece => !(piece.pos == pos2))
^


Why is this the case? Can I not reference a variable of type
Piece
with
.pos
?

Answer

This is happening because there are no getters set up for your Piece class.

// 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) 
Comments