Scala – View Bound

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:

  1. Upper Bound
  2. Lower Bound
  3. 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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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)
    }
}

chevron_right


Output:

25

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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)
    }
}

chevron_right


Output:

GeeksforGeeks



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.