Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does [+A] mean in Scala class declaration? [duplicate]

Tags:

types

scala

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.

like image 973
kikulikov Avatar asked Apr 02 '15 12:04

kikulikov


People also ask

What is the meaning of => in Scala?

=> is syntactic sugar for creating instances of functions. Recall that every function in scala is an instance of a class. For example, the type Int => String , is equivalent to the type Function1[Int,String] i.e. a function that takes an argument of type Int and returns a String .

What is [+ A in Scala?

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.


1 Answers

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.

like image 77
Ben Reich Avatar answered Oct 19 '22 07:10

Ben Reich