Skip to content
Tutorials Center
My learning

Topics

Lesson 73 of 134 ยท Idiomatic Kotlin

Annotations

Use and define Kotlin annotations: @Deprecated, @Suppress, @JvmStatic, @OptIn, targets and use-site targets, retention, reading annotations at run time and building a tiny test runner.

An annotation attaches metadata to a piece of code: a class, a function, a property, a parameter, even an expression. The metadata does nothing by itself. Something else reads it: the compiler (@Deprecated produces a warning), a tool (@Suppress silences it), or your own program at run time through reflection (a test runner looks for @Test). You meet annotations from the first day in Kotlin: @JvmStatic, @Deprecated, @Suppress, @OptIn, @Volatile, @Throws, and in frameworks @Composable, @Serializable or @Entity.

This lesson shows how to apply annotations, the built-in ones worth knowing, how to define your own with annotation class, what targets and retention mean, the use-site targets that surprise everybody (@get:, @field:), and how a program reads annotations while it runs. Examples use plain Java reflection, which works on the runner; the Kotlin-specific kotlin-reflect library does not, and the Reflection Overview lesson explains the difference.

Using annotations

You write @Name before the thing it applies to. Arguments go in parentheses, with the same positional and named syntax as function calls. Several annotations can stack. Annotations on a constructor need the explicit constructor keyword:

Kotlin
// read-only: the syntax of applying annotations
@Deprecated("Use newName()")
fun oldName() { }

@Suppress("UNUSED_VARIABLE", "unused")
fun demo() { val x = 1 }

class Service @Inject constructor(private val repo: Repo)   // needs the 'constructor' keyword

val total = @Suppress("UNCHECKED_CAST") (value as List<Int>) // annotating an expression

An annotation can also be applied to a whole file with @file:, placed before the package line (for example @file:JvmName("Utils"), which renames the generated class). The last line of the example is legal because expressions can be annotated, which is how a warning is silenced for exactly one cast.

@Deprecated: warn, then forbid

@Deprecated is the most useful built-in annotation, because it lets you retire an API without breaking callers at once. It takes a message, an optional ReplaceWith that an IDE can apply automatically, and a level: WARNING (the default), ERROR (the code no longer compiles) or HIDDEN (the declaration disappears from source, but stays for already compiled code).

Kotlin @Deprecated as a warning

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The program still runs and prints 6 twice. In a normal build the compiler also warns that sum is deprecated and shows the message you wrote (this page's runner displays only the program's output). In the IDE, the ReplaceWith expression becomes a one-click fix. Raise the level when everyone has had time to move:

Kotlin @Deprecated with level ERROR (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Now the build fails with main.kt:7:13: error: 'fun sum(items: List<Int>): Int' is deprecated. Removed in 2.0, use total(). The three-step schedule (warning, error, hidden or deleted) is how libraries evolve without surprising users.

Defining your own annotation

An annotation is a class declared with annotation class. Its constructor parameters are the arguments, limited to constants: primitives, strings, enums, class references, other annotations and arrays of those. Two meta-annotations describe it:

  • @Target(...) says where it may be applied: CLASS, FUNCTION, PROPERTY, FIELD, VALUE_PARAMETER, CONSTRUCTOR, EXPRESSION, TYPE, and so on. Applying it elsewhere is a compile error.
  • @Retention(...) says how long it survives: SOURCE (only in source, for tools like linters), BINARY (kept in the class file but invisible to reflection) or RUNTIME (visible to reflection). The default in Kotlin is RUNTIME.
Kotlin Define and read a runtime annotation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Report::class.java is the Java Class object for the Kotlin class, and getAnnotation is a plain Java reflection call, so no extra library is needed. The first annotation sets three arguments by name, the second uses the default version and tags and passes author positionally (the first constructor parameter). Arrays in annotation arguments use the square-bracket syntax ["a", "b"].

If you apply an annotation where its @Target does not allow it, you get a compile error that names the target. Try changing the example to put @Info("x") on a function:

Kotlin Wrong target (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The message is main.kt:5:5: error: this annotation is not applicable to target 'member function'. Applicable targets: class. Naming the allowed targets is therefore both documentation and a safety net. The default, when you give no @Target, is "almost everywhere", which tends to be too permissive for annotations that mean something specific.

A tiny test runner built from annotations

Annotations are what make frameworks possible. Here is the idea behind JUnit in thirty lines: a marker annotation, a class with annotated methods, and a runner that finds and calls them with Java reflection. The runner sorts methods by name because reflection does not guarantee an order.

Kotlin A miniature test framework

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

When a reflected call throws, Java wraps the exception in an InvocationTargetException; targetException gives the real one. Real test frameworks add lifecycle hooks, ordering, parameters and reporting, but the core is this: metadata is read, then acted on. Notice that @MyTest has no @Retention, so it is RUNTIME by default, which is what makes isAnnotationPresent see it. For testing in practice, see Testing in Kotlin.

Retention: SOURCE and BINARY are invisible at run time

Choosing the wrong retention is a classic bug: the annotation is there in the source, but the reader at run time finds nothing. Compare the three:

Kotlin Retention decides what reflection sees

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Only Visible is found (the last line lists Visible and Metadata, the annotation Kotlin itself adds to every class). Use SOURCE for markers that code generators or the compiler read, BINARY when other compiled modules or tools inspect the class file, and RUNTIME for anything your program reads while running. Runtime annotations cost a little class-file size and load time, so do not add them without a reader.

Use-site targets: which part of a property?

A Kotlin val name: String in a constructor is several things at once: a constructor parameter, a property, a field and a getter. When you write @Info on it, which one gets the annotation? Kotlin picks the first applicable of param, property, field, but frameworks often need the getter or the field, so you can say it with a use-site target: @get:, @set:, @field:, @param:, @property:, @file:, @delegate:.

Kotlin Where does an annotation land?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output shows that each annotation landed on exactly the element you named: name annotated on its field, email on its getter method, and age on the constructor parameter, with null everywhere else. Frameworks that use Java reflection (validation, JSON mapping, dependency injection) are why this matters: a @NotNull-style annotation put on the wrong element is silently ignored. When a framework tells you an annotation "does not work" on a Kotlin property, the use-site target is the first thing to check.

You can annotate with several targets at once using the bracket form: @get:[Mark("a") Other], or put @field: on each. Prefer a single clear target per annotation.

Annotations for Java interoperability

A group of built-in annotations exists only to shape the bytecode that Java code sees. You will use them in Java Interoperability. Their effect can be seen with Java reflection:

Kotlin @JvmStatic, @JvmField and @JvmOverloads change the bytecode

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The first line lists the static methods of Counter: create (from @JvmStatic, so Java can call Counter.create()) and a synthetic greet$default that Kotlin generates for default arguments. The second line shows that the companion class has both create and plain, so Kotlin callers are unaffected. The third line shows visible as a public field (@JvmField) while hidden stays private behind a getter and setter. The last line, [0, 1, 2], shows that greet exists with 0, 1 and 2 parameters (the 2-parameter one is the real function, the others are generated): @JvmOverloads generates one Java overload per default argument, since Java has no default parameters. @Throws(IOException::class) is the fourth one: Kotlin has no checked exceptions, but Java callers need the throws clause in the signature to be able to catch a checked exception. Other annotations you will see often: @Volatile and @Synchronized for threads, @JvmInline for value classes, @JvmName to rename a function in bytecode (useful to resolve a signature clash), and @DslMarker from the DSL lesson.

Opt-in annotations: marking unstable APIs

Library authors use a custom annotation, marked @RequiresOptIn, to say "this API may change; use it only if you accept that". Callers must either propagate the marker or opt in explicitly with @OptIn. You already saw @OptIn(ExperimentalContracts::class). Here is the whole mechanism with your own marker:

Kotlin Using an opt-in API without opting in (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler refuses with main.kt:9:13: error: this API is experimental and may change, which is the message you gave to @RequiresOptIn. Choose Level.WARNING instead of ERROR for a softer nudge. The fix is one of two annotations:

Kotlin Opting in, locally or by propagation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

@OptIn is the explicit "I know" at the place where you use the API, and the marker on your own function is how you pass the responsibility on. This is the same mechanism behind @ExperimentalStdlibApi, @ExperimentalCoroutinesApi and @DelicateCoroutinesApi.

Good habits

  • Read the compiler's deprecation messages; they usually show the replacement.
  • Suppress narrowly. @Suppress("UNCHECKED_CAST") on one expression is fine; on a whole file it hides real problems. Add a comment about why.
  • Give custom annotations a precise @Target and an explicit @Retention, so the intent is documented.
  • Do not invent annotations when a function parameter will do. Annotations are for cross-cutting metadata read by tools, not for ordinary program configuration.
  • Remember reflection costs. Scanning annotations at start-up is fine; doing it per request is slow. Cache the results.
  • Annotation arguments must be compile-time constants, so @Info(author = computeName()) does not compile.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does @Deprecated("Use total()", level = DeprecationLevel.ERROR) do to callers?

    At ERROR level the use of the declaration is a compile error that shows your message. WARNING only warns, and HIDDEN hides it from new source code.
  2. 2. An annotation is declared with @Retention(AnnotationRetention.SOURCE). What does cls.isAnnotationPresent(...) return at run time?

    SOURCE is discarded by the compiler. BINARY keeps it in the class file, but only RUNTIME makes it visible to reflection.
  3. 3. Which use-site target puts an annotation on the generated getter of a property?

    @get: targets the getter method, @field: the backing field, @param: the constructor parameter.
  4. 4. What does @JvmStatic on a companion object function change?

    Without it, Java calls Outer.Companion.method(). @JvmStatic adds a static method on the outer class.
  5. 5. Why do annotation arguments such as @Info(author = computeName()) not compile?

    Annotation values are stored in the class file, so they must be constants known at compile time: primitives, strings, enum entries, class references, other annotations and arrays of those.

Summary

  • An annotation is metadata, read by the compiler, tools or your program at run time.
  • @Deprecated (with ReplaceWith and a level) retires APIs gently; @Suppress silences specific warnings and should be narrow.
  • Define one with annotation class, limit it with @Target, and pick @Retention: SOURCE, BINARY or RUNTIME (the Kotlin default).
  • Use-site targets (@get:, @field:, @param:) decide which part of a property receives the annotation.
  • Java reflection (getAnnotation, isAnnotationPresent) reads runtime annotations and is enough for small frameworks like the test runner above.
  • @JvmStatic, @JvmField, @JvmOverloads and @Throws shape the bytecode for Java callers.
  • @RequiresOptIn and @OptIn mark and accept unstable APIs.

Next: Reflection Overview