Fahad/CodeSamples/GenericClasses.scala
author Christian Urban <christian dot urban at kcl dot ac dot uk>
Wed, 10 Jun 2015 14:51:35 +0100
changeset 79 ca8f9645db69
parent 44 a751aa1ee4f7
permissions -rw-r--r--
added frisch / cardelli paper
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
44
a751aa1ee4f7 Code Samples
Fahad Ausaf <fahad.ausaf@kcl.ac.uk>
parents:
diff changeset
     1
package Main
a751aa1ee4f7 Code Samples
Fahad Ausaf <fahad.ausaf@kcl.ac.uk>
parents:
diff changeset
     2
a751aa1ee4f7 Code Samples
Fahad Ausaf <fahad.ausaf@kcl.ac.uk>
parents:
diff changeset
     3
class Stack[T] {
a751aa1ee4f7 Code Samples
Fahad Ausaf <fahad.ausaf@kcl.ac.uk>
parents:
diff changeset
     4
  var elems: List[T] = Nil
a751aa1ee4f7 Code Samples
Fahad Ausaf <fahad.ausaf@kcl.ac.uk>
parents:
diff changeset
     5
  def push(x: T) { elems = x :: elems }
a751aa1ee4f7 Code Samples
Fahad Ausaf <fahad.ausaf@kcl.ac.uk>
parents:
diff changeset
     6
  def top: T = elems.head
a751aa1ee4f7 Code Samples
Fahad Ausaf <fahad.ausaf@kcl.ac.uk>
parents:
diff changeset
     7
  def pop() { elems = elems.tail }
a751aa1ee4f7 Code Samples
Fahad Ausaf <fahad.ausaf@kcl.ac.uk>
parents:
diff changeset
     8
}
a751aa1ee4f7 Code Samples
Fahad Ausaf <fahad.ausaf@kcl.ac.uk>
parents:
diff changeset
     9
a751aa1ee4f7 Code Samples
Fahad Ausaf <fahad.ausaf@kcl.ac.uk>
parents:
diff changeset
    10
object GenericsTest extends App{
a751aa1ee4f7 Code Samples
Fahad Ausaf <fahad.ausaf@kcl.ac.uk>
parents:
diff changeset
    11
  val stack = new Stack[Int]
a751aa1ee4f7 Code Samples
Fahad Ausaf <fahad.ausaf@kcl.ac.uk>
parents:
diff changeset
    12
  stack.push(1)
a751aa1ee4f7 Code Samples
Fahad Ausaf <fahad.ausaf@kcl.ac.uk>
parents:
diff changeset
    13
  stack.push('a')
a751aa1ee4f7 Code Samples
Fahad Ausaf <fahad.ausaf@kcl.ac.uk>
parents:
diff changeset
    14
  println(stack.top)
a751aa1ee4f7 Code Samples
Fahad Ausaf <fahad.ausaf@kcl.ac.uk>
parents:
diff changeset
    15
  stack.pop()
a751aa1ee4f7 Code Samples
Fahad Ausaf <fahad.ausaf@kcl.ac.uk>
parents:
diff changeset
    16
  println(stack.top)
a751aa1ee4f7 Code Samples
Fahad Ausaf <fahad.ausaf@kcl.ac.uk>
parents:
diff changeset
    17
}