101

EDIT: Re-written this question based on original answer

The scala.collection.immutable.Set class is not covariant in its type parameter. Why is this?

import scala.collection.immutable._

def foo(s: Set[CharSequence]): Unit = {
    println(s)
}

def bar(): Unit = {
   val s: Set[String] = Set("Hello", "World");
   foo(s); //DOES NOT COMPILE, regardless of whether type is declared 
           //explicitly in the val s declaration
}
2
  • It's worth noting that foo(s.toSet[CharSequence]) compiles fine. The toSet method is O(1) - it just wraps asInstanceOf. Sep 22, 2013 at 19:46
  • 1
    Note also that foo(Set("Hello", "World")) compiles too on 2.10, since Scala seems to be able to infer the right type of Set. It doesn't work with implicit conversions though (stackoverflow.com/questions/23274033/…). Apr 25, 2014 at 16:06

3 Answers 3

58

Set is invariant in its type parameter because of the concept behind sets as functions. The following signatures should clarify things slightly:

trait Set[A] extends (A=>Boolean) {
  def apply(e: A): Boolean
}

If Set were covariant in A, the apply method would be unable to take a parameter of type A due to the contravariance of functions. Set could potentially be contravariant in A, but this too causes issues when you want to do things like this:

def elements: Iterable[A]

In short, the best solution is to keep things invariant, even for the immutable data structure. You'll notice that immutable.Map is also invariant in one of its type parameters.

15
  • 4
    I guess this argument hinges around "the concept behind sets as functions" - could this be expanded upon? For example, what advantages does "a set as a function" give me that a "set as a collection" not? Is it worth losing the use of that covariant type? Mar 24, 2009 at 22:00
  • 23
    The type signature is a rather weak example. A set's "apply" is the same thing as it's contains method. Alas, Scala's List is co-variant and has a contains method as well. The signature for List's contains is different, of course, but the method works just like Set's. So there is nothing really stopping Set from being co-variant, except a design decision. Jul 24, 2009 at 2:44
  • 6
    Sets are not boolean functions from a mathematical perspective. Sets are "built up" from the Zermelo-Fraenkel axioms not reduced by some inclusion function. The reason behind this is Russell's paradox: if anything can be a member of a set, then consider the Set R of sets which are not members of themselves. Then ask the question, is R a member of R? Jan 11, 2010 at 22:39
  • 13
    I'm still unconvinced that sacrificing covariance was worth it for Set. Sure, it's nice that it's a predicate, but you can usually just be a little more verbose and use "set.contains" rather than "set" (and arguably "set.contains" reads better in many cases anyway).
    – Matt R
    Mar 3, 2011 at 20:32
  • 4
    @Martin: Because List's contains method takes Any, not A. The type of List(1,2,3).contains _ is (Any) => Boolean, while the type of Set(1,2,3).contains _ is res1: (Int) => Boolean.
    – Seth Tisue
    Jun 27, 2011 at 1:31
55

at http://www.scala-lang.org/node/9764 Martin Odersky writes:

"On the issue of sets, I believe the non-variance stems also from the implementations. Common sets are implemented as hashtables, which are non-variant arrays of the key type. I agree it's a slightly annoying irregularity."

So, it seems that all of our efforts to construct a principled reason for this were misguided :-)

3
  • 1
    But some sequences are also implemented with arrays, and still Seq is covariant... am I missing something? Apr 25, 2014 at 16:09
  • 4
    This could trivially be solved by storing Array[Any] internally.
    – user1804599
    Mar 9, 2015 at 16:26
  • @rightfold is correct. There might be a reasonable reason, but this isn't it. May 26, 2015 at 19:15
6

EDIT: for anyone wondering why this answer seems slightly off-topic, this is because I (the questioner) have modified the question.

Scala's type inference is good enough to figure out that you want CharSequences and not Strings in some situations. In particular, the following works for me in 2.7.3:

import scala.collections.immutable._
def findCharSequences(): Set[CharSequence] = Set("Hello", "World")

As to how to create immutable.HashSets directly: don't. As an implementation optimization, immutable.HashSets of less than 5 elements are not actually instances of immutable.HashSet. They are either EmptySet, Set1, Set2, Set3, or Set4. These classes subclass immutable.Set, but not immutable.HashSet.

1
  • You are right; in trying to simplify my actual example I made a trivial mistake :-( Mar 24, 2009 at 11:44

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.