In Scala a Set is a function:
trait Set[A] extends (A => Boolean)
This make it impossible to have a covariant immutable Set because type A occurs in contravariant position. In contrast Seq is not defined as a function. There is already some content about the question why Sets and Seqs are designed this way:
- Why is Scala’s immutable Set not covariant in its type?
- Scala: Why does Seq.contains take an Any argument, instead of an argument of the sequence type?
- Why does Seq.contains accept type Any rather than the type parameter A?
One answer says that the reason for this is the mathematical background. But this answer wasn’t explained a little more. So, what are the concrete advantages to define a Set as a function or what would be the disadvantages if it is implemented differently?
The set of type
Set[A]has to have a method that tests if an element of typeAis in the set. This method (apply) has to have a parameter of typeArepresenting that element, and that parameter is in the contravariant position. This means that sets cannot be covariant in their type parameterA. So – it’s not the extending of the function interface that makes it impossible to have covariant immutable sets, it’s the existence of the contravariantapplymethod.And for reasons of convenience, it makes sense to extend the
Function1interface to be able to pass sets around and treat them as functions.By contrast, sequence abstraction doesn’t have a method that tests if an element is in the sequence, it only has the indexing method –
applytakes an integer index, and returns the element at that index. Sequences are also defined as functions, but functions of typeInt => A(which are covariant inA), notA => Boolean, as sets.If you want to know more about how type safety would be broken if sets were defined as covariant in their type parameter
A, see this example in which the set implementation does some writing to private members for reasons of caching the lookups (below@uVis the annotation which disables variance checking andexpensiveLookupis meant to simulate a call to a computationally expensive check if an element is in the set):