Type Bounds in Scala are restrictions on type parameter or type variable. By the usage of these type bounds, we can set up limits for the variables. These bounds help to put up our code into real-world examples. We need to impose certain limitations and boundaries to every factor in real life, that is what the Type bounds do in Scala.
There are three types of types bounds supported in Scala:
Scala
Output:
Scala
Output:
- Upper Bound
- Lower Bound
- View Bound
[T <% S]Here, T is a type parameter and S is a type. <% denotes view bound. Below examples illustrate the concept of view bound in Scala: Example 1:
// Scala program to demonstrate view bound
// Declaration of view bound
class GFG[T <% Ordered[T]](val firstNumber: T,
val secondNumber: T)
{
def greaterNumber = if (firstNumber >
secondNumber)firstNumber
else secondNumber
}
// Object created
object ViewBoundExample
{
// Driver code
def main(args: Array[String])
{
val result = new GFG(24, 25)
println(result.greaterNumber)
}
}
25Example 2:
// Scala program to demonstrate view bound
// Declaration of view bound
class GFG[T <% Ordered[T]](val first_Str: T,
val second_Str: T)
{
def smaller_Str = if (first_Str <
second_Str)first_Str
else second_Str
}
// Object created
object ScalaViewBound
{
// Driver code
def main(args: Array[String])
{
val result = new GFG("GeeksforGeeks", "Scala")
println(result.smaller_Str)
}
}
GeeksforGeeks