Skip to content

Instantly share code, notes, and snippets.

@kmizu
Created May 18, 2010 03:24
Show Gist options
  • Save kmizu/404567 to your computer and use it in GitHub Desktop.
Save kmizu/404567 to your computer and use it in GitHub Desktop.
object BadStack {
class Stack[+A](elements: List[A]) {
def this() { this(Nil) }
def isEmpty: Boolean = elements == Nil
//push1 doesn't compile because the compiler cannot guarantee type safety.
//def push1(e: A): Stack[A] = new Stack(e::elements)
//push2 compiles.
def push2[B >: A](e: B): Stack[B] = new Stack(e::elements)
def pop: (A, Stack[A]) = elements match {
case x::xs => (x, new Stack(xs))
case Nil => error("pop cannot be called for empty stack")
}
def peek: A = elements match {
case x::xs => x
case Nil => error("peek cannot be called for empty stack")
}
}
def main(args: Array[String]) {
val strings: Stack[String] = new Stack("foo"::Nil)
val anys: Stack[Any] = strings //Because Stack is covariant, this line is OK.
// anys.push1(1) //If push1 compiles, this line breaks type safety.
anys.push2(1) //This line doens't break type safety.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment