Skip to content

Instantly share code, notes, and snippets.

@squito
Created July 3, 2013 19:20
Show Gist options
  • Save squito/5921876 to your computer and use it in GitHub Desktop.
Save squito/5921876 to your computer and use it in GitHub Desktop.
type variance & toMap
scala> trait A
defined trait A
scala>
scala> class B extends A
defined class B
scala> class C extends A
defined class C
//toMap a mix of B's & C's works fine
scala> (1 to 100).map{i => i -> {
| if (i % 2 == 0) new B() else new C()
| }}.toMap
res1: scala.collection.immutable.Map[Int,ScalaObject with A] = ...
//However, we have problems if we try to toMap something that is templated w/ a mix of B's & C's
scala> class D[T <: A]
defined class D
scala> (1 to 100).map{i => i -> {
| if (i % 2 == 0) new D[B]() else new D[C]()}
| }.toMap
<console>:13: error: Cannot prove that (Int, D[_1]) forSome { type _1 >: B with C <: ScalaObject with A } <:< (T, U).
if (i % 2 == 0) new D[B]() else new D[C]()}}.toMap
//But if we make the templated class covariant in T, then its happy again
scala> class E[+T <: A]
defined class E
scala> (1 to 100).map{i => i -> {
| if (i % 2 == 0) new E[B]() else new E[C]()}
| }.toMap
res3: scala.collection.immutable.Map[Int,E[ScalaObject with A]] = ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment