Skip to content

Instantly share code, notes, and snippets.

@lucianenache
Created April 4, 2019 21:29
Show Gist options
  • Save lucianenache/393768d7eac10b674b9937fb92a83be8 to your computer and use it in GitHub Desktop.
Save lucianenache/393768d7eac10b674b9937fb92a83be8 to your computer and use it in GitHub Desktop.
Scala stack example with mutable types
case class Node(data: Int, next: Option[Node]= None)
class Stack(var head: Node, var size: Int = 1) {
def push(i: Int): Unit = {
head = Node(i, Some(head))
size += 1
}
def pop(): Option[Int] = {
if(head == null) {
None
} else {
val r = Some(head.data)
head = head.next.getOrElse(null)
r
}
}
def dead = () //throw new NoSuchElementException("Stack.head")
}
object Stack {
def apply() = {
throw new InvalidArgumentException("Stack.head must be provided")
}
def apply(i: Int) = {
new Stack(Node(i))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment