scala.annotation

Members list

Packages

When defining a field, the Scala compiler creates up to four accessors for it: a getter, a setter, and if the field is annotated with @BeanProperty, a bean getter and a bean setter.

When defining a field, the Scala compiler creates up to four accessors for it: a getter, a setter, and if the field is annotated with @BeanProperty, a bean getter and a bean setter.

For instance in the following class definition

class C(@myAnnot @BeanProperty var c: Int)

there are six entities which can carry the annotation @myAnnot: the constructor parameter, the generated field and the four accessors.

By default, annotations on (val-, var- or plain) constructor parameters end up on the parameter, not on any other entity. Annotations on fields by default only end up on the field.

The meta-annotations in package scala.annotation.meta are used to control where annotations on fields and class parameters are copied. This is done by annotating either the annotation type or the annotation class with one or several of the meta-annotations in this package.

Annotating the annotation type

The target meta-annotations can be put on the annotation type when instantiating the annotation. In the following example, the annotation @Id will be added only to the bean getter getX.

import javax.persistence.Id
class A {
 @(Id @beanGetter) @BeanProperty val x = 0
}

In order to annotate the field as well, the meta-annotation @field would need to be added.

The syntax can be improved using a type alias:

object ScalaJPA {
 type Id = javax.persistence.Id @beanGetter
}
import ScalaJPA.Id
class A {
 @Id @BeanProperty val x = 0
}

Annotating the annotation class

For annotations defined in Scala, a default target can be specified in the annotation class itself, for example

@getter
class myAnnotation extends Annotation

This only changes the default target for the annotation myAnnotation. When instantiating the annotation, the target can still be specified as described in the last section.

Attributes

Type members

Classlikes

abstract class Annotation

A base class for annotations.

A base class for annotations.

Annotations extending this class directly are not preserved in the classfile. To enable storing annotations in the classfile's Scala signature and make it available to Scala reflection and other tools, the annotation needs to inherit from scala.annotation.StaticAnnotation.

Annotation classes defined in Scala are not stored in classfiles in a Java-compatible manner and therefore not visible in Java reflection. In order to achieve this, the annotation has to be written in Java.

Attributes

Source
Annotation.scala
Supertypes
class Object
trait Matchable
class Any
Known subtypes

Annotation classes extending this trait only accept constant values as arguments.

Annotation classes extending this trait only accept constant values as arguments.

Note that this trait extends StaticAnnotation, so constant annotations are persisted in the classfile.

The implementation requires arguments of constant annotations to be passed as named arguments, except if there is a single argument, which then defines the annotation's parameter named value.

Constant annotations may use default arguments. Note that the internal representation of an annotation usage (which is visible for compiler plugins, for example) only contains arguments that are explicitly provided.

Constant annotations are not allowed to define auxiliary constructors, and the primary constructor is required to have a single parameter list.

Example:

class Ann(value: Int, x: Int = 0) extends scala.annotation.ConstantAnnotation
class Test {
  def someInt = 0
  @Ann(value = 0, x = 1) def g = 0
  @Ann(0) def f = 0                 // Internal representation contains `@Ann(value = 0)`
  @Ann(someInt)                     // error: argument needs to be a compile-time constant
}

Attributes

Source
ConstantAnnotation.scala
Supertypes
class Annotation
class Object
trait Matchable
class Any
Known subtypes

A base trait for annotations that yield proper subtypes of the types they annotate. Refining annotations are more "sticky" than normal ones. They are conceptually kept around when normal refinements would also not be stripped away.

A base trait for annotations that yield proper subtypes of the types they annotate. Refining annotations are more "sticky" than normal ones. They are conceptually kept around when normal refinements would also not be stripped away.

Attributes

Source
RefiningAnnotation.scala
Supertypes
class Annotation
class Object
trait Matchable
class Any

A base class for static annotations.

A base class for static annotations. These are available to the Scala type checker or Scala reflection, even across different compilation units.

Annotation classes defined in Scala are not stored in classfiles in a Java-compatible manner and therefore not visible in Java reflection. In order to achieve this, the annotation has to be written in Java.

Attributes

Source
StaticAnnotation.scala
Supertypes
class Annotation
class Object
trait Matchable
class Any
Known subtypes
trait TypeConstraint extends Annotation

A marker for annotations that, when applied to a type, should be treated as a constraint on the annotated type.

A marker for annotations that, when applied to a type, should be treated as a constraint on the annotated type.

A proper constraint should restrict the type based only on information mentioned within the type. A Scala compiler can use this assumption to rewrite the contents of the constraint as necessary. To contrast, a type annotation whose meaning depends on the context where it is written down is not a proper constrained type, and this marker should not be applied. A Scala compiler will drop such annotations in cases where it would rewrite a type constraint.

Attributes

Source
TypeConstraint.scala
Supertypes
class Annotation
class Object
trait Matchable
class Any
final class compileTimeOnly(message: String) extends StaticAnnotation

An annotation that designates that an annottee should not be referred to after type checking (which includes macro expansion).

An annotation that designates that an annottee should not be referred to after type checking (which includes macro expansion).

Examples of potential use: 1) The annottee can only appear in the arguments of some other macro that will eliminate it from the AST during expansion. 2) The annottee is a macro and should have been expanded away, so if hasn't, something wrong has happened. (Comes in handy to provide better support for new macro flavors, e.g. macro annotations, that can't be expanded by the vanilla compiler).

Value parameters

message

the error message to print during compilation if a reference remains after type checking

Attributes

Source
compileTimeOnly.scala
Supertypes
class Annotation
class Object
trait Matchable
class Any

An annotation that goes on parameters of classes or traits. It asserts that the parameter is used only for initialization and is not kept in the class as a field. Violations of this assertion are flagged as compile errors. The annotation is particularly useful for implicit parameters since for these a textual scan is not sufficient to know where they are used. Note: the annotation is copied from constructor parameters to corresponding class fields. But it is checked that the field is eliminated before code is generated.

An annotation that goes on parameters of classes or traits. It asserts that the parameter is used only for initialization and is not kept in the class as a field. Violations of this assertion are flagged as compile errors. The annotation is particularly useful for implicit parameters since for these a textual scan is not sufficient to know where they are used. Note: the annotation is copied from constructor parameters to corresponding class fields. But it is checked that the field is eliminated before code is generated.

Attributes

Source
constructorOnly.scala
Supertypes
class Annotation
class Object
trait Matchable
class Any
final class elidable(val level: Int) extends ConstantAnnotation

An annotation for methods whose bodies may be excluded from compiler-generated bytecode.

An annotation for methods whose bodies may be excluded from compiler-generated bytecode.

Behavior is influenced by passing -Xelide-below <arg> to scalac. Calls to methods marked elidable (as well as the method body) will be omitted from generated code if the priority given the annotation is lower than that given on the command line.

@elidable(123)           // annotation priority
scalac -Xelide-below 456 // command line priority

The method call will be replaced with an expression which depends on the type of the elided expression. In decreasing order of precedence:

Unit            ()
Boolean         false
T <: AnyVal     0
T >: Null       null
T >: Nothing    Predef.???

Complete example:

import scala.annotation._, elidable._
object Test extends App {
  def expensiveComputation(): Int = { Thread.sleep(1000) ; 172 }

  @elidable(WARNING) def warning(msg: String) = println(msg)
  @elidable(FINE) def debug(msg: String)      = println(msg)
  @elidable(FINE) def computedValue           = expensiveComputation()

  warning("Warning! Danger! Warning!")
  debug("Debug! Danger! Debug!")
  println("I computed a value: " + computedValue)
}
% scalac example.scala && scala Test
Warning! Danger! Warning!
Debug! Danger! Debug!
I computed a value: 172

// INFO lies between WARNING and FINE
% scalac -Xelide-below INFO example.scala && scala Test
Warning! Danger! Warning!
I computed a value: 0

Note that only concrete methods can be marked @elidable. A non-annotated method is not elided, even if it overrides / implements a method that has the annotation.

Also note that the static type determines which annotations are considered:

import scala.annotation._, elidable._
class C { @elidable(0) def f(): Unit = ??? }
object O extends C { override def f(): Unit = println("O.f") }
object Test extends App {
  O.f()      // not elided
  (O: C).f() // elided if compiled with `-Xelide-below 1`
}

Attributes

Companion
object
Source
elidable.scala
Supertypes
class Annotation
class Object
trait Matchable
class Any
Show all
object elidable

This useless appearing code was necessary to allow people to use named constants for the elidable annotation.

This useless appearing code was necessary to allow people to use named constants for the elidable annotation. This is what it takes to convince the compiler to fold the constants: otherwise when it's time to check an elision level it's staring at a tree like

(Select(Level, Select(FINEST, Apply(intValue, Nil))))

instead of the number 300.

Attributes

Companion
class
Source
elidable.scala
Supertypes
class Object
trait Matchable
class Any
Self type
elidable.type

An annotation that can be used to mark a definition as experimental.

An annotation that can be used to mark a definition as experimental.

Attributes

See also
Source
experimental.scala
Supertypes
class Annotation
class Object
trait Matchable
class Any
final class implicitAmbiguous(msg: String) extends ConstantAnnotation

To customize the error message that's emitted when an implicit search finds multiple ambiguous values, annotate at least one of the implicit values @implicitAmbiguous.

To customize the error message that's emitted when an implicit search finds multiple ambiguous values, annotate at least one of the implicit values @implicitAmbiguous. Assuming the implicit value is a method with type parameters X1,..., XN, the error message will be the result of replacing all occurrences of ${Xi} in the string msg with the string representation of the corresponding type argument Ti.

If more than one @implicitAmbiguous annotation is collected, the compiler is free to pick any of them to display.

Nice errors can direct users to fix imports or even tell them why code intentionally doesn't compile.

trait =!=[C, D]

implicit def neq[E, F] : E =!= F = null

@annotation.implicitAmbiguous("Could not prove ${J} =!= ${J}")
implicit def neqAmbig1[G, H, J] : J =!= J = null
implicit def neqAmbig2[I] : I =!= I = null

implicitly[Int =!= Int]

Attributes

Source
implicitAmbiguous.scala
Supertypes
class Annotation
class Object
trait Matchable
class Any
Show all
final class implicitNotFound(msg: String) extends ConstantAnnotation

To customize the error message that's emitted when an implicit of type C[T1,..., TN] cannot be found, annotate the class C with @implicitNotFound.

To customize the error message that's emitted when an implicit of type C[T1,..., TN] cannot be found, annotate the class C with @implicitNotFound. Assuming C has type parameters X1, ..., XN, the error message will be the result of replacing all occurrences of ${Xi} in the string msg with the string representation of the corresponding type argument Ti. The annotation is effectively inherited by subtypes if they are not annotated.

The annotation can also be attached to implicit parameters. In this case, ${Xi} can refer to type parameters in the current scope. The @implicitNotFound message on the parameter takes precedence over the one on the parameter's type.

import scala.annotation.implicitNotFound

@implicitNotFound("Could not find an implicit C[${T}, ${U}]")
class C[T, U]

class K[A] {
  def m[B](implicit c: C[List[A], B]) = 0
  def n[B](implicit @implicitNotFound("Specific message for C of list of ${A} and ${B}") c: C[List[A], B]) = 1
}

object Test {
  val k = new K[Int]
  k.m[String]
  k.n[String]
}

The compiler issues the following error messages:

Test.scala:13: error: Could not find an implicit C[List[Int], String]
 k.m[String]
    ^
Test.scala:14: error: Specific message for C of list of Int and String
 k.n[String]
    ^

Attributes

Source
implicitNotFound.scala
Supertypes
class Annotation
class Object
trait Matchable
class Any
Show all
class nowarn(value: String) extends ConstantAnnotation

An annotation for local warning suppression.

An annotation for local warning suppression.

The optional value parameter allows selectively silencing messages, see scalac -Wconf:help for help. Examples:

def f = {
  1: @nowarn // don't warn "a pure expression does nothing in statement position"
  2
}

@nowarn def f = { 1; deprecated() } // don't warn

@nowarn("msg=pure expression does nothing")
def f = { 1; deprecated() } // show deprecation warning

To ensure that a @nowarn annotation actually suppresses a warning, enable -Xlint:unused or -Wunused:nowarn. The unused annotation warning is emitted in category unused-nowarn and can be selectively managed using -Wconf:cat=unused-nowarn:s.

Attributes

Source
nowarn.scala
Supertypes
class Annotation
class Object
trait Matchable
class Any
Show all
class showAsInfix(enabled: Boolean) extends StaticAnnotation

This annotation configures how Scala prints two-parameter generic types.

This annotation configures how Scala prints two-parameter generic types.

By default, types with symbolic names are printed infix; while types without them are printed using the regular generic type syntax.

Example of usage:

scala> class Map[T, U]
defined class Map

scala> def foo: Int Map Int = ???
foo: Map[Int,Int]

scala> @showAsInfix class Map[T, U]
defined class Map

scala> def foo: Int Map Int = ???
foo: Int Map Int

Value parameters

enabled

whether to show this type as an infix type operator.

Attributes

Source
showAsInfix.scala
Supertypes
class Annotation
class Object
trait Matchable
class Any
final class static extends StaticAnnotation

https://github.com/scala/scala.github.com/pull/491

class strictfp extends StaticAnnotation

If this annotation is present on a method or its enclosing class, the strictfp flag will be emitted.

If this annotation is present on a method or its enclosing class, the strictfp flag will be emitted.

Attributes

Source
strictfp.scala
Supertypes
class Annotation
class Object
trait Matchable
class Any
final class switch extends StaticAnnotation

An annotation to be applied to a match expression.

An annotation to be applied to a match expression. If present, the compiler will verify that the match has been compiled to a tableswitch or lookupswitch and issue a warning if it instead compiles into a series of conditional expressions. Example usage:

val Constant = 'Q'
def tokenMe(ch: Char) = (ch: @switch) match {
  case ' ' | '\t' | '\n'  => 1
  case 'A' | 'Z' | '$'    => 2
  case '5' | Constant     => 3  // a non-literal may prevent switch generation: this would not compile
  case _                  => 4
}

Note: for pattern matches with one or two cases, the compiler generates jump instructions. Annotating such a match with @switch does not issue any warning.

Attributes

Source
switch.scala
Supertypes
class Annotation
class Object
trait Matchable
class Any
final class tailrec extends StaticAnnotation

A method annotation which verifies that the method will be compiled with tail call optimization.

A method annotation which verifies that the method will be compiled with tail call optimization.

If it is present, the compiler will issue an error if the method cannot be optimized into a loop.

Attributes

Source
tailrec.scala
Supertypes
class Annotation
class Object
trait Matchable
class Any
final class targetName(name: String) extends StaticAnnotation

An annotation that defines an external name for a definition. If an targetName(extname) annotation is given for a method or some other definition, its implementation will use the name extname instead of the regular name.

An annotation that defines an external name for a definition. If an targetName(extname) annotation is given for a method or some other definition, its implementation will use the name extname instead of the regular name.

Attributes

Source
targetName.scala
Supertypes
class Annotation
class Object
trait Matchable
class Any
final class threadUnsafe extends StaticAnnotation

This annotation can only be used on a field which defines a lazy val. When this annotation is used, the initialization of the lazy val will use a faster mechanism which is not thread-safe.

This annotation can only be used on a field which defines a lazy val. When this annotation is used, the initialization of the lazy val will use a faster mechanism which is not thread-safe.

Attributes

Source
threadUnsafe.scala
Supertypes
class Annotation
class Object
trait Matchable
class Any
final class transparentTrait extends StaticAnnotation

An annotation that can be used from Scala 2 to mark a trait as transparent. Scala 3 code would use the modifier transparent instead. Transparent traits are not inferred when combined with other types in an intersection. See reference/other-new-features/transparent-traits.html for details.

An annotation that can be used from Scala 2 to mark a trait as transparent. Scala 3 code would use the modifier transparent instead. Transparent traits are not inferred when combined with other types in an intersection. See reference/other-new-features/transparent-traits.html for details.

Attributes

Source
transparentTrait.scala
Supertypes
class Annotation
class Object
trait Matchable
class Any

A method annotation which suppresses the creation of additional specialized forms based on enclosing specialized type parameters.

A method annotation which suppresses the creation of additional specialized forms based on enclosing specialized type parameters.

Attributes

Source
unspecialized.scala
Supertypes
class Annotation
class Object
trait Matchable
class Any
class unused(message: String) extends StaticAnnotation

Mark an element unused for a given context.

Mark an element unused for a given context.

Unused warnings are suppressed for elements known to be unused.

For example, a method parameter may be marked @unused because the method is designed to be overridden by an implementation that does use the parameter.

Attributes

Source
unused.scala
Supertypes
class Annotation
class Object
trait Matchable
class Any
final class varargs extends StaticAnnotation

A method annotation which instructs the compiler to generate a Java varargs-style forwarder method for interop.

A method annotation which instructs the compiler to generate a Java varargs-style forwarder method for interop. This annotation can only be applied to methods with repeated parameters.

Attributes

Source
varargs.scala
Supertypes
class Annotation
class Object
trait Matchable
class Any

Deprecated classlikes

A base class for classfile annotations.

A base class for classfile annotations. These are stored as Java annotations in classfiles.

Attributes

Deprecated
true
Source
ClassfileAnnotation.scala
Supertypes
class Annotation
class Object
trait Matchable
class Any
Show all
final class alpha(externalName: String) extends StaticAnnotation

An annotation that defines an external name for a definition. If an alpha(extname) annotation is given for a method or some other definition, its implementation will use the name extname instead of the regular name. An alpha annotation is mandatory for definitions with symbolic names.

An annotation that defines an external name for a definition. If an alpha(extname) annotation is given for a method or some other definition, its implementation will use the name extname instead of the regular name. An alpha annotation is mandatory for definitions with symbolic names.

Attributes

Deprecated
true
Source
alpha.scala
Supertypes
class Annotation
class Object
trait Matchable
class Any

Experimental classlikes

trait MainAnnotation[Parser[_], Result] extends StaticAnnotation

MainAnnotation provides the functionality for a compiler-generated main class. It links a compiler-generated main method (call it compiler-main) to a user written main method (user-main). The protocol of calls from compiler-main is as follows:

MainAnnotation provides the functionality for a compiler-generated main class. It links a compiler-generated main method (call it compiler-main) to a user written main method (user-main). The protocol of calls from compiler-main is as follows:

  • create a command with the command line arguments,
  • for each parameter of user-main, a call to command.argGetter, or command.varargGetter if is a final varargs parameter,
  • a call to command.run with the closure of user-main applied to all arguments.

Example:

/** Sum all the numbers
 *
 *  @param first Fist number to sum
 *  @param rest The rest of the numbers to sum
 */
@myMain def sum(first: Int, second: Int = 0, rest: Int*): Int = first + second + rest.sum

generates

object foo {
  def main(args: Array[String]): Unit = {
    val mainAnnot = new myMain()
    val info = new Info(
      name = "foo.main",
      documentation = "Sum all the numbers",
      parameters = Seq(
        new Parameter("first", "scala.Int", hasDefault=false, isVarargs=false, "Fist number to sum"),
        new Parameter("rest", "scala.Int" , hasDefault=false, isVarargs=true, "The rest of the numbers to sum")
      )
    )
    val mainArgsOpt = mainAnnot.command(info, args)
    if mainArgsOpt.isDefined then
      val mainArgs = mainArgsOpt.get
      val args0 = mainAnnot.argGetter[Int](info.parameters(0), mainArgs(0), None) // using parser Int
      val args1 = mainAnnot.argGetter[Int](info.parameters(1), mainArgs(1), Some(() => sum$default$1())) // using parser Int
      val args2 = mainAnnot.varargGetter[Int](info.parameters(2), mainArgs.drop(2)) // using parser Int
      mainAnnot.run(() => sum(args0(), args1(), args2()*))
  }
}

Value parameters

Parser

The class used for argument string parsing and arguments into a T

Result

The required result type of the main method. If this type is Any or Unit, any type will be accepted.

Attributes

Companion
object
Experimental
true
Source
MainAnnotation.scala
Supertypes
class Annotation
class Object
trait Matchable
class Any
Known subtypes
class newMain

Attributes

Companion
trait
Experimental
true
Source
MainAnnotation.scala
Supertypes
class Object
trait Matchable
class Any
Self type
final class capability extends StaticAnnotation

Marks an annotated class as a capability. If the annotation is present and -Ycc is set, any (possibly aliased or refined) instance of the class type is implicitly augmented with the universal capture set. Example

Marks an annotated class as a capability. If the annotation is present and -Ycc is set, any (possibly aliased or refined) instance of the class type is implicitly augmented with the universal capture set. Example

Attributes

Experimental
true
Source
capability.scala
Supertypes
class Annotation
class Object
trait Matchable
class Any
final class newMain extends MainAnnotation[FromString, Any]

The annotation that designates a main function. Main functions are entry points for Scala programs. They can be called through a command line interface by using the scala command, followed by their name and, optionally, their parameters.

The annotation that designates a main function. Main functions are entry points for Scala programs. They can be called through a command line interface by using the scala command, followed by their name and, optionally, their parameters.

The parameters of a main function may have any type T, as long as there exists a given util.CommandLineParser.FromString[T] in the scope. It will be used for parsing the string given as input into the correct argument type. These types already have parsers defined:

  • String,
  • Boolean,
  • Byte, Short, Int, Long, Float, Double.

The parameters of a main function may be passed either by position, or by name. Passing an argument positionally means that you give the arguments in the same order as the function's signature. Passing an argument by name means that you give the argument right after giving its name. Considering the function @newMain def foo(i: Int, str: String), we may have arguments passed:

  • by position: scala foo 1 abc,
  • by name: scala foo -i 1 --str abc or scala foo --str abc -i 1.

A mixture of both is also possible: scala foo --str abc 1 is equivalent to all previous examples.

Note that main function overloading is not currently supported, i.e. you cannot define two main methods that have the same name in the same project.

Special arguments are used to display help regarding a main function: --help and -h. If used as argument, the program will display some useful information about the main function. This help directly uses the ScalaDoc comment associated with the function, more precisely its description and the description of the parameters documented with @param. Note that if a parameter is named help or h, or if one of the parameters has as alias one of those names, the help displaying will be disabled for that argument. For example, for @newMain def foo(help: Boolean), scala foo -h will display the help, but scala foo --help will fail, as it will expect a Boolean value after --help.

Parameters may be given annotations to add functionalities to the main function:

  • main.alias adds other names to a parameter. For example, if a parameter node has as aliases otherNode and n, it may be addressed using --node, --otherNode or -n.

Here is an example of a main function with annotated parameters: @newMain def foo(@newMain.alias("x") number: Int, @newMain.alias("explanation") s: String). The following commands are equivalent:

  • scala foo --number 1 -s abc
  • scala foo -x 1 -s abc
  • scala foo --number 1 --explanation abc
  • scala foo -x 1 --explanation abc

Boolean parameters are considered flags that do not require the "true" or "false" value to be passed. For example, @newMain def foo(i: Boolean) can be called as foo (where i=false) or foo -i (where i=true).

The special -- marker can be used to indicate that all following arguments are passed verbatim as positional parameters. For example, @newMain def foo(args: String*) can be called as scala foo a b -- -c -d which implies that args=Seq("a", "b", "-c", "-d").

Attributes

Companion
object
Experimental
true
Source
newMain.scala
Supertypes
class Annotation
class Object
trait Matchable
class Any
Show all
object newMain

Attributes

Companion
class
Experimental
true
Source
newMain.scala
Supertypes
class Object
trait Matchable
class Any
Self type
newMain.type
class retains(xs: Any*) extends StaticAnnotation

An annotation that indicates capture of a set of references under -Ycc.

An annotation that indicates capture of a set of references under -Ycc.

T @retains(x, y, z)

is the internal representation used for the capturing type

{x, y, z}  T

The annotation can also be written explicitly if one wants to avoid the non-standard capturing type syntax.

Attributes

Experimental
true
Source
retains.scala
Supertypes
class Annotation
class Object
trait Matchable
class Any
class retainsByName(xs: Any*) extends StaticAnnotation

An annotation that indicates capture of an enclosing by-name type

An annotation that indicates capture of an enclosing by-name type

Attributes

Experimental
true
Source
retainsByName.scala
Supertypes
class Annotation
class Object
trait Matchable
class Any