I'm trying to understand how to use implicits in Scala: In my code I have:
trait Cell
class EnemyCell extends Cell
class RectangleCell extends Serializable with Cell
I defined a trait Placeable and I wanted it to have a subtype of cell
trait Placeable[A <: Cell] {
def place(a: A, cell:Option[RectangleCell],controller:MapController ): Unit
}
I then defined the object:
object Placeable {
//Apply
def apply[A <: Cell](implicit pleaceable: Placeable[A ]): Placeable[A] = pleaceable
def place[A: Placeable](a: A, cell:Option[RectangleCell], controller:MapController) = Placeable[A].place(a, cell, controller)
def instance[A <: Cell](func: (A, Option[RectangleCell], MapController) => Unit): Placeable[A] =
new Placeable[A] {
def place(a: A, cell:Option[RectangleCell] , controller: MapController): Unit = func(a, cell, controller)
}
//These 2 def does not seem to do anything...
implicit def cellToEnemyCell(cell: Cell): EnemyCell = cell.asInstanceOf[EnemyCell];
implicit def cellToRectangleCell(cell: Cell): RectangleCell = cell.asInstanceOf[RectangleCell];
implicit val rectanglePlaceable: Placeable[RectangleCell] =
instance((selected, cell, controller) => {
...
})
implicit val enemyPlaceable: Placeable[EnemyCell] =
instance((selected, cell, controller) => {
...
})
}
The problem is that I am getting the error:
Error:(75, 98) type arguments [A] do not conform to method apply's type parameter bounds [A <: model.Cell]
def place[A: Placeable](a: A, cell:Option[RectangleCell], controller:MapController) = Placeable[A].place(a, cell, controller)
All I wanted was to use:
var _selected:Option[Cell] = Option.empty; //I edit this in my code and it can be either a RectangleCell or a EnemyCell
...
val tmpRect = _selected.get
place(tmpRect,cell,this)
instead of doing:
if(_selected.get.isInstanceOf[RectangleCell]) {
val tmpRect = _selected.get.asInstanceOf[RectangleCell]
place(tmpRect,cell,this)
} else {
val tmpRect = _selected.get.asInstanceOf[EnemyCell]
place(tmpRect,cell,this)
}
Thank you in advance!