Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

scala

What are lower type bounds in Scala?

Ayesha Naeem

Lower type bounds in Scala define limitations on type parameters or type variables.

Syntax

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.

Examples

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 Truck
class Car extends Truck {
override def name: String = "Car"
}
// subclass of Car and Truck
class Bicycle extends Car {
override def name: String = "Bicyle"
}
// lower bound type is Car
class Transport[T >: Car](t: T) {
def transport : T = t
}

object LowerTypeBounds extends App {
    
// create class instances
val 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 Truck
class Car extends Truck {
override def name: String = "Car"
}
// subclass of Car and Truck
class Bicycle extends Car {
override def name: String = "Bicyle"
}
// lower bound type is Car
class Transport[T >: Car](t: T) {
def transport : T = t
}

object LowerTypeBounds extends App {
val ride = new Transport[Bicycle](new Bicycle)



}

RELATED TAGS

scala

CONTRIBUTOR

Ayesha Naeem
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring