Skip to content

Instantly share code, notes, and snippets.

@ajaybgupta
Created April 4, 2018 09:19
Show Gist options
  • Save ajaybgupta/d69de473dfd0c8d9c19d94e9564b3838 to your computer and use it in GitHub Desktop.
Save ajaybgupta/d69de473dfd0c8d9c19d94e9564b3838 to your computer and use it in GitHub Desktop.
Generics Example in Scala
/** Test One
*
* Created by Ajay Gupta on 04/04/18.
*/
object TestOne {
def main(args: Array[String]): Unit = {
val employee1 = Employee(1, "Sourab")
val employee2 = Employee(2, "Ajay")
val employeeStack = new Stack[Employee]
employeeStack.push(employee1)
employeeStack.push(employee2)
val employee = employeeStack.pop()
println(employee)
val manager1 = Manager(1, "Manager1", 11)
val manager2 = Manager(2, "Manager2", 12)
val managerStack = new Stack[Manager]
managerStack.push(manager1)
managerStack.push(manager2)
val manager = managerStack.pop()
println(manager)
}
}
case class Employee(id: Int, name: String)
case class Manager(id: Int, name: String, managesEmployee: Int)
class Stack[A] {
private var elements: List[A] = Nil
def push(x: A) {
elements = x :: elements
}
def peek: A = elements.head
def pop(): A = {
val currentTop = peek
elements = elements.tail
currentTop
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment