Created
April 4, 2019 21:29
-
-
Save lucianenache/393768d7eac10b674b9937fb92a83be8 to your computer and use it in GitHub Desktop.
Scala stack example with mutable types
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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