Upper type bounds in Scala define limitations on type parameters or type variables.
The upper bound on a type parameter in Scala is defined through the following syntax:
T
is a type parameter subjected to the constraint that it must be of either type A
or a sub-type of A
.
The following code demonstrates how to use upper type parameters in Scala:
abstract class Vehicle {def name: String}class Truck extends Vehicle {override def name: String = "Truck"}//sub class of Truckclass Car extends Truck {override def name: String = "Car"}//not a sub class of Truckclass Bicycle extends Vehicle {override def name: String = "Bicyle"}// upper bound type is Truckclass Transport[T <: Truck](t: T) {def transport : T = t}object UpperTypeBounds extends App {//creates instanceval ride = new Transport[Truck](new Truck)val ride_second = new Transport[Car](new Car)}
In the above code, the type of transport class must be either Truck
or a sub-type of Truck
,
i.e., Car
.
The above code compiles successfully because Transport
class instances are created using Truck
and Car
types, which fulfill the condition.
However, the following code fails to compile because it creates the Transport
class instance with type Bicycle
, which is not a sub-type of Truck
.
abstract class Vehicle {def name: String}class Truck extends Vehicle {override def name: String = "Truck"}class Car extends Truck {override def name: String = "Car"}class Bicycle extends Vehicle {override def name: String = "Bicyle"}class Transport[T <: Truck](t: T) {def transport : T = t}object UpperTypeBounds extends App {val ride = new Transport[Bicycle](new Bicycle)}
Free Resources