#generic-classes #scala
subtyping of generic types is *invariant*. This means that if we have a stack of characters of type Stack[Char]
then it cannot be used as an integer stack of type Stack[Int]
. This would be unsound because it would enable us to enter true integers into the character stack.
If you want to change selection, open document below and click on "Move attachment"
Generic Classes - Scala Documentationpe.
Here are some usage examples:
object GenericsTest extends App {
val stack = new Stack[Int]
stack.push(1)
stack.push('a')
println(stack.top)
stack.pop()
println(stack.top)
}
The output of this program will be:
97
1
Note: <span>subtyping of generic types is *invariant*. This means that if we have a stack of characters of type Stack[Char] then it cannot be used as an integer stack of type Stack[Int]. This would be unsound because it would enable us to enter true integers into the character stack. To conclude, Stack[T] is only a subtype of Stack[S] if and only if S = T. Since this can be quite restrictive, Scala offers a type parameter annotation mechanism to control the subtyping Summary
status | not read | | reprioritisations | |
---|
last reprioritisation on | | | suggested re-reading day | |
---|
started reading on | | | finished reading on | |
---|
Details