Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Generics Type Constraints

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.

like image 665
Travis Parks Avatar asked Apr 01 '13 16:04

Travis Parks


People also ask

What is a generic class in Scala?

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.

What are generalized type constraints?

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.

What is the upper bound type in Scala generics?

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].

How to compare XS list elements in Scala generics?

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.


1 Answers

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.

like image 107
Randall Schulz Avatar answered Oct 14 '22 06:10

Randall Schulz