Skip to content

Instantly share code, notes, and snippets.

@oreillyross
Created August 5, 2015 10:56
Show Gist options
  • Save oreillyross/7aca197e38ed3bc423ef to your computer and use it in GitHub Desktop.
Save oreillyross/7aca197e38ed3bc423ef to your computer and use it in GitHub Desktop.
In Scala, arrays are invariant by default and immutable collections (or container types) are covariant or [+A]. Since they are immutable all of your potential type errors will be discovered during compile time as opposed to runtime. Another possible option is to define a container as contravariant ([-A]). Contravariance means that a container wi…
case class InvariantContainer[A]()
case class CovariantContainer[+A]()
case class ContravariantContainer[-A]()
class Person
class User extends Person
class Admin extends User
val inv1: InvariantContainer[User] = InvariantContainer[User] // works
val inv2: InvariantContainer[User] = InvariantContainer[Admin] // doesn't work
val cov1: CovariantContainer[User] = CovariantContainer[User] // works
val cov2: CovariantContainer[User] = CovariantContainer[Admin] // works
val con1: ContravariantContainer[User] = ContravariantContainer[User] // works
val con2: ContravariantContainer[User] = ContravariantContainer[Admin] // doesn't work
val con3: ContravariantContainer[User] = ContravariantContainer[Person] // works
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment