Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameters to a trait

Tags:

scala

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?

like image 414
octavian Avatar asked Aug 17 '16 10:08

octavian


People also ask

Can trait have parameters?

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.

How many ways the parameters can be passed?

Parameters can be passed to a method in following three ways : Value Parameters. Reference Parameters. Output Parameters.

What is the difference between trait and class?

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.


1 Answers

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
like image 106
0__ Avatar answered Oct 04 '22 14:10

0__