Skip to content

Instantly share code, notes, and snippets.

@gakuzzzz
Last active November 16, 2022 03:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gakuzzzz/d8d6069d28825fb7d04a46992f94b90b to your computer and use it in GitHub Desktop.
Save gakuzzzz/d8d6069d28825fb7d04a46992f94b90b to your computer and use it in GitHub Desktop.
Scala variance sample
class Foo[+A]
class Bar[-A]

class Test1[A] {
  def piyo(a: A): Unit = ???      // OK
  def poyo(a: Foo[A]): Unit = ??? // OK
  def puyo(a: Bar[A]): Unit = ??? // OK

  def paya(): A = ???             // OK
  def poya(): Foo[A] = ???        // OK
  def puya(): Bar[A] = ???        // OK
}
class Test2[+A] {
  def piyo(a: A): Unit = ???      // NG
  def poyo(a: Foo[A]): Unit = ??? // NG
  def puyo(a: Bar[A]): Unit = ??? // OK

  def paya(): A = ???             // OK
  def poya(): Foo[A] = ???        // OK
  def puya(): Bar[A] = ???        // NG
}
class Test3[-A] {
  def piyo(a: A): Unit = ???      // OK
  def poyo(a: Foo[A]): Unit = ??? // OK
  def puyo(a: Bar[A]): Unit = ??? // NG

  def paya(): A = ???             // NG
  def poya(): Foo[A] = ???        // NG
  def puya(): Bar[A] = ???        // OK
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment