Lower type bounds in Scala define limitations on type parameters or type variables.
The lower 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 either of type A
or a super-type of A
.
The following code demonstrates how to use lower type parameters in Scala:
abstract class Vehicle {def name: String}class Truck extends Vehicle {override def name: String = "Truck"}// sub-classof Truckclass Car extends Truck {override def name: String = "Car"}// subclass of Car and Truckclass Bicycle extends Car {override def name: String = "Bicyle"}// lower bound type is Carclass Transport[T >: Car](t: T) {def transport : T = t}object LowerTypeBounds extends App {// create class instancesval ride = new Transport[Car](new Bicycle)val ride_second = new Transport[Truck](new Truck)}
In the above code, the type parameter of transport class must be either Car
or a super-type of Car,
i.e., Truck
.
The above code compiles successfully because Transport
class instances are created using Truck
and Car
types, which fulfills that condition.
However, the following code fails to compile because it creates the Transport
class instance with the type Bicycle
, which is a sub-type of Truck
.
abstract class Vehicle {def name: String}class Truck extends Vehicle {override def name: String = "Truck"}// sub-classof Truckclass Car extends Truck {override def name: String = "Car"}// subclass of Car and Truckclass Bicycle extends Car {override def name: String = "Bicyle"}// lower bound type is Carclass Transport[T >: Car](t: T) {def transport : T = t}object LowerTypeBounds extends App {val ride = new Transport[Bicycle](new Bicycle)}
Free Resources