Question

How to Use Links and Code Formatting in Kotlin KDoc

kotlindocumentationkdoc

Question

I am trying to document a Kotlin method and want to use @link and @code the way they are used in JavaDoc.

I understand that Kotlin uses KDoc, but I cannot find these tags or an equivalent syntax. What is the Kotlin KDoc way to create links and format code inside documentation comments?

Short Answer

By the end of this page, you will understand how Kotlin KDoc handles references and code formatting without using JavaDoc tags like @link and @code. You will learn the Markdown-based syntax KDoc uses, how to link to classes, functions, and properties, and how to write clear inline code and code blocks in Kotlin documentation.

Concept

KDoc is Kotlin’s documentation format. It looks similar to JavaDoc because it uses /** ... */ comments, but its syntax is different in an important way: KDoc uses Markdown for most formatting.

That means:

  • JavaDoc-style tags such as @code are generally replaced by Markdown code formatting.
  • Links are usually written with KDoc link syntax instead of JavaDoc’s {@link ...} style.

Why this matters

Good documentation helps other developers:

  • understand how to call your function
  • know what types and values are expected
  • navigate quickly to related classes and methods
  • read examples more easily

If you come from Java, the biggest adjustment is that KDoc is more Markdown-like and less tag-heavy.

The key idea

In Kotlin KDoc:

  • Use backticks for inline code: `value`
  • Use fenced or indented code blocks for larger examples
  • Use square brackets for links: [MyClass], [myFunction]
  • You can also provide custom link text: [visible text][MyClass]

So instead of JavaDoc tags, KDoc relies on a simpler, more readable writing style.

Mental Model

Think of KDoc as JavaDoc comments with Markdown inside.

  • In JavaDoc, you often use special commands like {@link Something} and {@code x + y}.
  • In KDoc, you write more naturally:
    • links look like references in Markdown
    • code looks like code in Markdown

A useful analogy is:

  • JavaDoc = filling a form with special commands
  • KDoc = writing notes with lightweight formatting

So if you want to mention a class, function, or property, you usually wrap it in square brackets. If you want to show code, you wrap it in backticks or put it in a code block.

Take Quiz

Syntax and Examples

Core syntax

Inline code

Use backticks for inline code:

/**
 * Returns `true` if `name` is not empty.
 */
fun hasName(name: String): Boolean = name.isNotEmpty()

Linking to a symbol

Use square brackets to link to a class, function, or property:

/**
 * Calls [saveUser] after validating the input.
 */
fun processUser() {
    saveUser()
}

fun saveUser() {}

Custom link text

You can display custom text while linking to a symbol:

/**
 * Use [the save operation][saveUser] to persist the data.
 */
fun processUser() {
    saveUser()
}

fun saveUser() {}

Code block example

/**
 * Example:
 * ```
 * val valid = hasName("Ada")
 * println(valid)
 * ```
 */
fun hasName(name: String): Boolean = name.isNotEmpty()

JavaDoc vs KDoc mindset

JavaDoc style:

/**
 * Calls {@link #saveUser()} with {@code name}.
 */

KDoc style:

/**
 * Calls [saveUser] with `name`.
 */

Beginner-friendly example

/**
 * Formats a user's display name.
 *
 * Use [trim] before calling this function if the input may contain spaces.
 * The returned value is wrapped in `[]`.
 *
 * Example:
 * ```
 * val result = formatName("Ada")
 * println(result) // [Ada]
 * ```
 */
fun formatName(name: String): String {
    return "[$name]"
}

What this shows

  • [trim] is a link-style reference
  • `[]` is inline code formatting
  • triple backticks create a code block
  • the comment stays readable even without generated docs

Step by Step Execution

Consider this example:

/**
 * Sends data to [saveRecord].
 * Returns `true` when the operation succeeds.
 */
fun send(): Boolean {
    saveRecord()
    return true
}

fun saveRecord() {}

Step by step

  1. The /** ... */ block tells Kotlin tools that this is a documentation comment.
  2. Inside the comment, [saveRecord] is treated as a reference to the saveRecord function.
  3. The text `true` is formatted as inline code, not as a normal word.
  4. When documentation is generated, tools can turn [saveRecord] into a clickable reference if the symbol can be resolved.
  5. The function send() runs normally at runtime. KDoc does not affect program behavior.
  6. Documentation comments are for developers, IDE hints, and generated docs.

Important takeaway

KDoc formatting is processed by documentation tools and IDEs, but it does not change what your Kotlin code does when it executes.

Real World Use Cases

1. Documenting API methods

When writing a service or library, you often want to point users to related methods:

/**
 * Loads a user by ID.
 * See also [loadAllUsers].
 */
fun loadUser(id: Int) {}

2. Explaining expected parameter values

Inline code is useful for showing exact values:

/**
 * Pass `null` to use the default configuration.
 */
fun connect(config: String?) {}

3. Adding usage examples to reusable functions

Code blocks make examples easier to understand:

/**
 * Example:
 * ```
 * retry(3) {
 *     fetchData()
 * }
 * ```
 */
fun retry(times: Int, action: () -> Unit) {}

4. Documenting SDKs and shared libraries

In team codebases, developers often link related types:

/**
 * Maps a network model to [User].
 */
fun mapUser() {}

class User

5. Improving IDE help

KDoc appears in tooltips and autocomplete documentation. Using links and code formatting makes that help more readable and easier to navigate.

Take Quiz

Real Codebase Usage

In real projects, developers use KDoc links and code formatting in a few common patterns.

Related-function references

When one function should be used before or after another, developers link them directly:

/**
 * Validates the request before calling [submitOrder].
 */
fun validateOrder() {}

Guard clauses and validation rules

KDoc is often used to document exact invalid values or required states:

/**
 * Throws an exception if `email` is blank.
 */
fun requireEmail(email: String) {}

Configuration and defaults

Developers document defaults using inline code because exact values matter:

/**
 * The timeout is `30_000` milliseconds by default.
 */
val defaultTimeout = 30_000

Error handling notes

Functions that can fail often document related exceptions or recovery paths:

/**
 * Call [close] when processing is complete.
 */
fun open() {}

fun close() {}

Public library documentation

Libraries rely heavily on:

  • symbol links like [Result]
  • inline code like `false`
  • short code examples in fenced blocks
  • parameter docs such as @param, @return, and @throws

A practical pattern is to combine them:

/**
 * Parses a value into [Result].
 *
 * @param input the raw value; must not be `""`
 * @return a parsed [Result]
 */
fun parse(input: String): Result<String> = Result.success(input)

Common Mistakes

1. Using JavaDoc syntax directly in KDoc

A common mistake is writing JavaDoc tags inside Kotlin docs.

Broken example:

/**
 * Calls {@link saveUser} with {@code name}.
 */
fun process(name: String) {}

Preferred KDoc style:

/**
 * Calls [saveUser] with `name`.
 */
fun process(name: String) {}

2. Forgetting that KDoc uses Markdown-style code formatting

Broken example:

/**
 * Returns true if input is valid.
 */

Better example:

/**
 * Returns `true` if `input` is valid.
 */

Using backticks makes exact values and identifiers stand out.

3. Writing unresolved links

If the symbol cannot be found, the link may not resolve correctly.

/**
 * Calls [saveUsr].
 */
fun process() {}

If the real function is saveUser, the reference should match that symbol.

4. Overusing links

Not every word needs to be a link.

Too much:

/**
 * Converts [String] to [Int] and returns [null] on failure.
 */

Clearer:

/**
 * Converts a string to an `Int` and returns `null` on failure.
 */

5. Using code blocks for tiny pieces of code

For single values or identifiers, inline code is better than a full block.

Less ideal:

/**
 * Pass
 * ```
 * null
 * ```
 * to reset the state.
 */

Better:

/**
 * Pass `null` to reset the state.
 */

6. Assuming KDoc changes runtime behavior

KDoc only documents code. It does not validate inputs, enforce rules, or change execution.

Comparisons

ConceptJavaDocKDoc
Inline code{@code value}`value`
Link to symbol{@link MyClass}[MyClass]
Custom link textlimited tag-based style[text][MyClass]
General formattingtag-heavyMarkdown-based
Code examplesoften tag-based or plain textfenced code blocks

Inline code vs links

Use whenSyntaxExample
You want to show code textbackticks`null`
You want to reference a symbolsquare brackets[User]

When to use each

  • Use inline code for:

    • literals like true, null, 0
    • parameter names like name
    • short expressions like a + b
  • Use links for:

    • classes
    • functions
    • properties
    • related APIs the reader may want to open

KDoc tags that still exist

KDoc does still support documentation tags such as:

  • @param
  • @return
  • @throws
  • @constructor
  • @property

So the difference is not that KDoc has no tags at all. The difference is that formatting and references are usually written with Markdown-style syntax instead of JavaDoc inline tags.

Take Quiz

Cheat Sheet

Quick reference

Inline code

/**
 * Uses `null` when no value is provided.
 */

Link to a symbol

/**
 * See [UserService].
 */

Link with custom text

/**
 * Use [the service layer][UserService].
 */

Code block

/**
 * Example:
 * ```
 * val user = loadUser(1)
 * ```
 */

Rules to remember

  • KDoc uses /** ... */
  • Use backticks for inline code
  • Use square brackets for links
  • Use fenced code blocks for longer examples
  • Use tags like @param and @return for structured docs
  • Do not rely on JavaDoc inline tags like {@code ...} and {@link ...}

Common conversions from JavaDoc

JavaDocKDoc
{@code name}`name`
{@link MyClass}[MyClass]
{@link myFunction}[myFunction]

Edge cases

  • A link only works well if the symbol can be resolved.
  • Inline code does not create navigation; it only formats text.
  • KDoc improves IDE and generated docs, but does not affect runtime behavior.

FAQ

Can I use @link in Kotlin KDoc?

KDoc does not normally use JavaDoc-style @link or {@link ...} syntax. Use [SymbolName] instead.

What is the Kotlin equivalent of JavaDoc @code?

Use Markdown-style backticks, such as `value` or `null`.

How do I link to a function in KDoc?

Write the function name in square brackets, such as [saveUser], as long as the symbol can be resolved.

How do I show a full code example in KDoc?

Use a fenced code block inside the documentation comment with triple backticks.

Does KDoc still support tags like @param and @return?

Yes. KDoc still supports structured tags such as @param, @return, and @throws.

Why are square brackets used in KDoc?

Square brackets are the KDoc way to express references to symbols, similar to Markdown links but resolved against Kotlin code.

What if a KDoc link does not work?

Check that the symbol name is correct and available in the documentation context. Unresolved or misspelled names may not generate proper links.

Take Quiz

Mini Project

Description

Create a small Kotlin file containing a few documented functions and a class using proper KDoc syntax. The project demonstrates how to replace JavaDoc-style @link and @code usage with Kotlin-friendly KDoc links, inline code, and code blocks.

Goal

Write readable KDoc comments that link to Kotlin symbols and format code examples correctly.

Requirements

  • Create at least one class and two functions in Kotlin.
  • Add KDoc that links from one function to another using square brackets.
  • Use inline code formatting for values like null, true, or parameter names.
  • Include at least one fenced code example inside a KDoc comment.
Take Quiz

Keep learning

Related questions

View more