ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

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:

[email protected]
!
[email protected]
Roars!
ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.