Home »
Scala
Upper Bound in Scala
By IncludeHelp Last updated : November 16, 2024
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.
Example of Upper Bound
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): Unit = {
println(d.voice)
}
}
object ScalaUpperBounds {
def main(args: Array[String]): Unit = {
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
!
!
Roars!
Roars!