Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identify and describe Scala's generic type constraints

Tags:

generics

scala

I've seen <:, >:, <%, etc. Can someone give (or locate) a good description of these? What are the possible constraints, what do they do, and what's an example of when to use them?

like image 870
Alex Black Avatar asked Feb 02 '11 01:02

Alex Black


People also ask

What are generic type constraints?

C# allows you to use constraints to restrict client code to specify certain types while instantiating generic types. It will give a compile-time error if you try to instantiate a generic type using a type that is not allowed by the specified constraints.

What does the generic constraint of type interface do?

Interface Type Constraint You can constrain the generic type by interface, thereby allowing only classes that implement that interface or classes that inherit from classes that implement the interface as the type parameter.

What is generic type arguments?

The generic argument list is a comma-separated list of type arguments. A type argument is the name of an actual concrete type that replaces a corresponding type parameter in the generic parameter clause of a generic type. The result is a specialized version of that generic type.

What is type constraint?

A type constraint on a generic type parameter indicates a requirement that a type must fulfill in order to be accepted as a type argument for that type parameter. (For example, it might have to be a given class type or a subtype of that class type, or it might have to implement a given interface.)


1 Answers

S <: T means that S is a subtype of T. This is also called an upper type bound. Similarly, S >: T means that S is a supertype of T, a lower type bound.

S <% T is a view bound, and expresses that S must come equipped with a view that maps its values into values of type T.

It's confusing for me too, and I have a Masters in programming languages from Berkeley.

like image 64
Raph Levien Avatar answered Sep 24 '22 17:09

Raph Levien