8

In scala Option class is declared like

  sealed abstract class _Option[+A]

  case object _None extends _Option[Nothing] {}

  final case class _Some[+A](x: A) extends _Option[A] {}

What is [+A]? Why not just [A]? Could it be [-A] and what it would mean?

Sorry if it is a duplicate but I couldn't find the answer on SO.

Ben Reich
  • 16,222
  • 2
  • 38
  • 59
kikulikov
  • 2,512
  • 4
  • 29
  • 45
  • Those are variance annotations. As a rule of thumb you should spend some time getting the hang of the language before rushing to SO. The scala info page on this very site (http://stackoverflow.com/tags/scala/info) has a lot of pointers to learning material. Concerning variance, see by example http://www.artima.com/pins1ed/type-parameterization.html. – Régis Jean-Gilles Apr 02 '15 at 12:34
  • 1
    @EndeNeu yes, the content of the question is similar... But you will never find the right answer if you do not know what "covariance" is. – kikulikov Apr 02 '15 at 12:34
  • That's a very good point. Which is why you need to invest some time on some learning material first (even if only by skimming over it). – Régis Jean-Gilles Apr 02 '15 at 12:36

1 Answers1

13

It declares the class to be covariant in its generic parameter. For your example, it means that Option[T] is a subtype of Option[S] if T is a subtype of S. So, for example, Option[String] is a subtype of Option[Object], allowing you to do:

val x: Option[String] = Some("a")
val y: Option[Object] = x

Conversely, a class can be contravariant in its generic parameter if it is declared as -A.

Read above variances in Scala in the docs here.

Ben Reich
  • 16,222
  • 2
  • 38
  • 59