-
Notifications
You must be signed in to change notification settings - Fork 0
/
ScalaGenericsTest.scala
46 lines (38 loc) · 988 Bytes
/
ScalaGenericsTest.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package com.training.generics
object ScalaGenericsTest {
def main(args: Array[String])
{
// val stackInt = new Stack[Int]
// stackInt.push(1)
// stackInt.push(2)
//
//
// println(stackInt.pop) // prints 2
// println(stackInt.pop) // prints 1
val stackFruit = new Stack[Fruit]
val apple = new Apple
val banana = new Banana
stackFruit.push(apple)
stackFruit.push(banana)
println(stackFruit.pop) // prints Banana
println(stackFruit.pop) // prints Apple
}
}
class Stack[R] {
private var elements: List[R] = Nil
def push(x: R) { elements = x :: elements }
def peek: R = elements.head
def pop(): R = {
//println("peek=>" + peek)
val currentTop = peek
//println("currentTop=>" + currentTop)
elements = elements.tail
//println("elements=>" + elements)
//println("currentTop=>" + currentTop)
currentTop
}
}
/**/
class Fruit
class Apple extends Fruit
class Banana extends Fruit