Skip to content

Instantly share code, notes, and snippets.

@asethia
Last active June 15, 2018 20:20
Show Gist options
  • Save asethia/e53bf3360963a8c1d6b35bfa2043b2cf to your computer and use it in GitHub Desktop.
Save asethia/e53bf3360963a8c1d6b35bfa2043b2cf to your computer and use it in GitHub Desktop.
Linked List Using Scala
package linkedlist
sealed trait AbstractCons[+A] {
def value: A
def next: AbstractCons[A]
}
/**
* cons class
* @param value
* @param next
* @tparam A
*/
case class Cons[+A](value: A, next: AbstractCons[A]) extends AbstractCons[A] {
override def toString = s"head: $value, next: $next"
}
/**
* Nil to indicate end of list
*/
object NilCons extends AbstractCons[Nothing] {
def value = throw new NoSuchElementException("it is empty")
def next = throw new UnsupportedOperationException("tail of empty list")
}
/**
* example to run the linked list
*/
object LinkedList extends App {
/**
* Operation :: for Any
* @param value1
* @tparam A
*/
implicit class ConsAny[+A](value1: A) {
def ::[A](value2: A) = Cons(value2, Cons(value1, NilCons))
}
/**
* Operation :: for AbstractCons
* @param value1
* @tparam A
*/
implicit class ConsOps[+A](value1: AbstractCons[A]) {
def ::[A](value2: A) = Cons(value2, value1)
}
val linkedList: Cons[Any] =("test1")::("test2")::("test3")::("test4")
println(linkedList)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment