Scala – View Bound
Last Updated :
03 Jul, 2020
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:
- Upper Bound
- Lower Bound
- View Bound
Here we will discuss view bound.
View Bound is one of the type bound used in Scala. View bound is basically used where existing implicit conversions are used automatically. In some programs, to solve any problem implicit conversions are done automatically. View bound is used to take advantage of these implicit conversions.
Syntax:
[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:
class GFG[T <% Ordered[T]]( val firstNumber : T,
val secondNumber : T)
{
def greaterNumber = if (firstNumber >
secondNumber)firstNumber
else secondNumber
}
object ViewBoundExample
{
def main(args : Array[String])
{
val result = new GFG( 24 , 25 )
println(result.greaterNumber)
}
}
|
Output:
25
Example 2:
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 ScalaViewBound
{
def main(args : Array[String])
{
val result = new GFG( "GeeksforGeeks" , "Scala" )
println(result.smaller _ Str)
}
}
|
Output:
GeeksforGeeks
Share your thoughts in the comments
Please Login to comment...