Scala upper constraint

Let’s go back to Object Oriented Programming concepts and specifically to interfaces (trait).

We are going to see how to constraint what type can be passed on. Several constraints are possible, let’s talk about a upper bound. The technical term for it is Upper Type Bounds but let’s keep it simple.

The new operator we are looking at today is <:

The syntax is A <: B and it means that the type A must be B or a class that has inherited from B, a child class.

The main advantage of doing this is that if you were to only have a simple generic class [A], you would not know anything about A at compile time. However, if you bound it, using [A <: B], the compiler would know that A is at least a B. That allow you to write code that can use the fields and methods of B as if A was B.

Extra note, when defining a custom type using type, it is possible to describe in a parent class as type MYTYPE <: CONSTRAINT so that child class has to implement it with a type that is a child of CONSTRAINT.

trait ParentClassOfConstraint

class ChildClassOfConstraint extends ParentClassOfConstraint

trait Foo {
   type MYTYPE <: ParentClassOfConstraint

class Bar extends Foo {
   override type MYTYPE = ChildClassOfConstraint

It is a bit advanced but I thought you should know about it.

Reveal more information and clues
Load Exercise