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 isUpper Type Boundsbut let's keep it simple.

The new operator we are looking at today is<:

The syntax isA <: Band it means that the typeAmust beBor a class that has inherited fromB, 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 aboutAat compile time. However, if youboundit, using[A <: B], the compiler would know thatAisat leastaB. That allow you to write code that can use the fields and methods ofBas ifAwasB.

Extra note, when defining a custom type usingtype, it is possible to describe in a parent class astype MYTYPE <: CONSTRAINTso that child class has to implement it with a type that is a child ofCONSTRAINT.

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