I want to model the game of chess.
For that, I want to make an abstract class, Piece
which takes a player and a position as arguments. From that, I want to extend to other classes such as Pawn
:
trait Piece(player: Int, pos: Pos) = {
def spaces(destination: Pos): List[Pos]
}
case class Pawn extends Piece = {
//some other code
}
However, I think I'm not allowed to pass parameters to a trait, like this trait Piece(player: Int, pos: Pos)
.
So how can I have an abstract class Piece
that has fields?
A Trait is a concept pre-dominantly used in object-oriented programming, which can extend the functionality of a class using a set of methods. Traits are similar in spirit to interfaces in Java programming language. Unlike a class, Scala traits cannot be instantiated and have no arguments or parameters.
Parameters can be passed to a method in following three ways : Value Parameters. Reference Parameters. Output Parameters.
Trait supports multiple inheritance. Abstract Class supports single inheritance only. Trait can be added to an object instance. Abstract class cannot be added to an object instance.
You could use an abstract class
abstract class Piece(player: Int, pos: Pos) {
...
}
case class Pawn(player: Int, pos: Pos) extends Piece(player, pos)
Or (probably better) you define those members abstractly in a trait
trait Piece {
def player: Int
def pos: Pos
...
}
case class Pawn(player: Int, pos: Pos) extends Piece
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With