Trying to implement a LinkedList in Scala. I'm quite comfortable with creating an immutable List as an ADT in scala like the following.
sealed trait List[+A]
case object Nil extends List[Nothing]
case class Cons[+A](head: A, tail: List[A]) extends List[A]
But trying to create a java style linkedlist with "null" termination seems very hard in scala, given there is a null reference in Scala.
I tried the following
sealed trait Node[+A]
case object Empty extends Node[Nothing]
case class LinkedList[A](var head: A,var tail: Node[A]) extends Node[A]
LinkedList is a case class with mutable members, seems very wrong to me. But since I would have to differentiate between Empty and LinkedList before every operation, i need the help of pattern matching.
Is this the right way to do it? or is there an better way to do it?
Also in the second example i'm not able to have a co-variant type like this
case class LinkedList[+A](var head: A,var tail: Node[A]) extends Node[A]
Listclass is an immutable linked list, and is implemented very similarly to your ADT.