Created
August 5, 2015 10:56
-
-
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…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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