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 <: B
and it means that the typeA
must beB
or 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 aboutA
at compile time. However, if youboundit, using[A <: B]
, the compiler would know thatA
isat leastaB
. That allow you to write code that can use the fields and methods ofB
as ifA
wasB
.
Extra note, when defining a custom type usingtype
, it is possible to describe in a parent class astype MYTYPE <: CONSTRAINT
so 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.