Home »
Scala
Upper Bound in Scala
Scala | Upper bound: Here, we will learn about the upper bounds in Scala programming language. We will see them working using programs.
Submitted by Shivang Yadav, on February 02, 2021
Upper bound
The Upper bound is a type bound in Scala which is used on type variables in order to analyze the type condition bounding these type values.
Syntax:
[T <: N]
Here, T is a type parameter; S is a type.
The upper bound implements that T can either be sub-type of S or can be of the type same as S.
Program to illustrate the working of our solution
abstract class Animals {
def voice: String
}
class Wild extends Animals {
override def voice: String = "!"
}
class Lion extends Wild {
override def voice: String = "Roars!"
}
class Forest {
def display [T <: Wild](d : T) {
println(d)
}
}
object ScalaUpperBounds {
def main(args: Array[String]) {
val wildAnimal = new Wild
val lion = new Lion
val forest = new Forest
forest.display(wildAnimal)
println(wildAnimal.voice)
forest.display(lion)
println(lion.voice)
}
}
Output:
Wild@1fc793c2
!
Lion@2575f671
Roars!