I want to implement some kind of a simple linked list.
I defined an abstract No, with a field next, its type is Node.
Then I have a bunch of other specific Node, inheriting the abstract node.
I write like this:
abstract class Node {
def next: Node
}
case class SpecificNode(nxt: Node) extends Node {
val next = nxt
}
object NullNode extends Node{
val next = new Exception("no more node")
}
However, I find that I need to change the field next later, in the SpecificNode,
so I make
case class SpecificNode(nxt: Node) extends Node {
var next = nxt
}
However, I can not assign to the next field of an instance of some specific node ,e.g sn.next = ..., because the compiler complains next_ is not a member of Node.
Then I changed to use var in the abstract class Node for the next field.
But when I new a NullNode, exception will be thrown (since I defined so..)
So how should I use the var, def, val here?
How should I define the NullNode, which is to signify no more node?
You need to explicitly define getter/setter in your interface. In our case (without changing structure and idea):
Side note: this is mutable linked list, I suggest you to check how immutable list implemented in standard scala library