I have the following code:
trait CellT[VAL <: AnyVal] {
var value: VAL
type NEXT <: AnyVal
var next: CellT[NEXT]
}
abstract class Cell[VAL <: AnyVal] extends CellT[VAL] {
var next = this // defaults to `this`. ERROR
}
// impl example:
class CellInt extends Cell[Int] {
var value: Int = 0
}
The error says that
overriding variable next in trait CellT of type
Cell[Cell.this.NEXT]; variable next has
incompatible type
Here it is obvious that this will have the type VAL <: AnyVal which is the same as NEXT <: AnyVal, however, I still get the error. How can I tell Scala that next should be able to return anything of type Cell[A <: AnyVal], but this type should not be necessary the same as the class type parameter [VAL <: AnyVal]??? Otherwise I could just use [VAL] but it will be too restrictive, for example for Cell[Int] it will restrict the next method to return only Cell[Int] type instances. But I want the next to be reassignable to any other Cell[*] types instances.
If you want
nextto be reassignable to any other Cell[*] types instances, you can use existential types:Output:
Cell(0,this)
Cell(1,this)
Cell(1,Cell(false,this))
Cell(false,this)
Cell(1,Cell(true,this))
Cell(true,this)