I am reading Programming Scala right now. I just got through the chapter on implicit type conversion, where the <%
symbol is introduced. There is also a <:
symbol and a <
symbol.
Could someone please summarize the different type constraints? I am struggling with the difference between <:
and <
for instance. I am curious if there are any others I haven't covered yet.
Generic classes (or traits) take a type as a parameter within square brackets [...] . The Scala convention is to use a single letter (like A) to name those type parameters. The type can then be used inside the class as needed for method instance parameters, or on return types: This implementation of a Stack class takes any type as a parameter.
And here is where the Generalized type constraints come into play: The three existing generalized type constraints are =:=, <: <and <% <. They are used by implicit parameters (implicit ev: T =:= B) in the method. These implicit parameters, generally called ev (“evidences”) are tests, which show that a type meets certain restrictions.
As it turns out, the upper bound type in Scala generics will do this for us: With the “T <: Ordered [T]” syntax we indicate that Ordered [T] is the supertype of type parameter T. That is, each element in the xs list should be a subtype of Ordered [T].
As it turns out, the upper bound type in Scala generics will do this for us: With the “T <: Ordered [T]” syntax we indicate that Ordered [T] is the supertype of type parameter T. That is, each element in the xs list should be a subtype of Ordered [T]. This way, we can use >= and other comparison functions with them.
There is no type constraint called <
.
A <: B
means A
is literally a subtype of B
(where subtype is defined reflexively, meaning for any type T
it is the case that T <: T
).
A <% B
means A
is either a subtype of B
or there is an implicit conversion from A
to a distinct type AA
for which AA <: B
. This is called a "view bound."
A >: B
means A
is supertype of B
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With