Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

scala

What are upper type bounds in Scala?

Ayesha Naeem

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

Syntax

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.

Examples

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 Truck
class Car extends Truck {
override def name: String = "Car"
}

//not a sub class of Truck
class Bicycle extends Vehicle {
override def name: String = "Bicyle"
}

// upper bound type is Truck
class Transport[T <: Truck](t: T) {
def transport : T = t
}

object UpperTypeBounds extends App {
    //creates instance  
val 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)



}

RELATED TAGS

scala

CONTRIBUTOR

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

View all Courses

Keep Exploring