What does [B >: A] mean in Scala? And what are the effects?
Example reference: http://www.scala-lang.org/node/129
class Stack[+A] {
def push[B >: A](elem: B): Stack[B] = new Stack[B] {
override def top: B = elem
override def pop: Stack[B] = Stack.this
override def toString() = elem.toString() + " " + Stack.this.toString()
}
def top: A = error("no element on stack")
def pop: Stack[A] = error("no element on stack")
override def toString() = ""
}
object VariancesTest extends Application {
var s: Stack[Any] = new Stack().push("hello");
s = s.push(new Object())
s = s.push(7)
println(s)
}
[B >: A]is a lower type bound. It means thatBis constrained to be a supertype ofA.Similarly
[B <: A]is an upper type bound, meaning thatBis constrained to be a subtype ofA.In the example you’ve shown, you’re allowed to push an element of type
Bonto a stack containingAelements, but the result is a stack ofBelements.The page where you saw this actually has a link to another page about lower type bounds, which includes an example showing the effect.