Comments and documentation
suggest changeKotlin has three kinds of comments:
// line comments/* block comments */, which nest, unlike in Java/** KDoc comments */, which document declarations and can be turned into HTML by Dokka
This article covers the comment syntax, how to write KDoc (block tags, links, Markdown, samples), and how to generate API docs with Dokka from Gradle or the command line.
Line and block comments
// A line comment runs to the end of the line.
/* A block comment
can span several lines. */
/*
* Block comments nest in Kotlin, so you can comment out
* a region that already contains a comment:
*
* /* old version */
* fun oldArea(w: Int, h: Int) = w * h
*/
fun area(w: Int, h: Int): Int = w * h // trailing comment
fun main() {
val total = area(3, /* height = */ 4)
println("total = $total")
val s = "// not a comment, /* also not */ just text"
println(s)
val url = "https://example.com" // the // inside the string is fine
println(url)
}
Output:
total = 12
// not a comment, /* also not */ just text
https://example.com
Comment markers inside string literals are just text.
A short block comment such as /* height = */ can label an argument in the middle of a line. In Kotlin you'll usually use a named argument instead: area(3, h = 4). The compiler checks names, it doesn't check comments.
Nesting gotcha
Because block comments nest, every /* inside a block comment opens another level, and each level needs its own */. A glob pattern in a comment is enough to break compilation:
/* Deletes everything under build/* */
fun clean() {}
fun main() {
clean()
println("done")
}
glob.kt:8:1: error: syntax error: Unclosed comment.
build/* opens a nested comment, the */ closes it, and the outer comment is never closed. Java would accept this code. The same happens in KDoc, even inside backticks: /** Deletes `build/*`. */ doesn't compile either. Use line comments for text like this, or reword it ("everything in the build directory").
The lexer doesn't know about strings inside comments either. Commenting out val end = "*/" with /* ... */ ends the comment early. Line comments (Ctrl+/ in IntelliJ IDEA and Android Studio) are the safest way to disable code.
Shebang line
A Kotlin script (.main.kts) can start with a shebang line so Unix shells can run it directly. #! is allowed only on the first line:
#!/usr/bin/env kotlin
// hello.main.kts
println("args: ${args.toList()}")
$ kotlin hello.main.kts a b
args: [a, b]
KDoc
A KDoc comment starts with /** and is placed right before a class, function, property, type alias or object. Its text is Markdown, plus block tags that start with @.
The first paragraph is the summary. IDEs show it in completion popups and Dokka shows it in member lists. Write the rest of the description after a blank line, then the block tags.
Here is a fully documented class:
package com.example.stack
/**
* A last-in, first-out stack that holds at most [capacity] elements.
*
* Pushing onto a full stack drops the oldest element, which makes
* `BoundedStack` handy for undo history and "recently used" lists:
*
* ```kotlin
* val history = BoundedStack<String>(capacity = 2)
* history.push("a")
* history.push("b")
* history.push("c") // "a" is dropped
* ```
*
* This class is **not** thread-safe. Wrap it in a lock or use
* [java.util.concurrent.ConcurrentLinkedDeque] when several threads share it.
*
* @param T the type of elements in the stack.
* @property capacity the maximum number of elements; must be positive.
* @constructor Creates an empty stack.
* @throws IllegalArgumentException if [capacity] is zero or negative.
* @see peek
* @sample com.example.stack.samples.undoHistory
*/
class BoundedStack<T>(val capacity: Int) {
private val items = ArrayDeque<T>()
init {
require(capacity > 0) { "capacity must be positive, was $capacity" }
}
/** The number of elements currently in the stack. */
val size: Int get() = items.size
/**
* Pushes [element] onto the top of the stack.
*
* If the stack is already full, the bottom (oldest) element
* is removed first.
*
* @param element the value to push.
* @return the dropped element, or `null` if nothing was dropped.
*/
fun push(element: T): T? {
val dropped = if (items.size == capacity) items.removeFirst() else null
items.addLast(element)
return dropped
}
/**
* Removes and returns the top element.
*
* @throws NoSuchElementException if the stack is empty.
*/
fun pop(): T = items.removeLast()
/** Returns the top element without removing it, or `null` if the stack is empty. */
fun peek(): T? = items.lastOrNull()
fun clear() = items.clear()
}
/**
* Pushes every element of [elements] onto this stack, in order.
*
* @receiver the stack to push onto.
* @return this stack, for chaining.
* @since 1.1
*/
fun <T> BoundedStack<T>.pushAll(elements: Iterable<T>): BoundedStack<T> {
elements.forEach { push(it) }
return this
}
Short members get a one-line /** ... */. Don't add @param and @return tags that only repeat the signature. peek() doesn't need @return the top element.
KDoc is not available at runtime. Comments never reach the .class file, so you can't read them through reflection. Use annotations if you need metadata at runtime (see Declaring an annotation).
Block tags
| Tag | Meaning |
|---|---|
@param name |
a function parameter or a type parameter (@param T) |
@property name |
a property declared in the primary constructor |
@return |
the return value |
@constructor |
the primary constructor |
@receiver |
the receiver of an extension function |
@throws Class / @exception Class |
an exception the function can throw |
@sample fqName |
embeds the body of a function as an example |
@see name |
adds a "See also" link |
@author, @since |
author and version that introduced the API |
@suppress |
hides the element from generated docs |
A primary constructor parameter can be documented with either tag. Use @property for val/var parameters and @param for plain constructor parameters that don't become properties.
Kotlin has no checked exceptions, so @throws is the only place callers learn what can go wrong. Document exceptions that are part of the contract, such as IllegalArgumentException from require(). Add the @Throws annotation as well if Java code calls the function and needs to catch a checked exception.
KDoc doesn't support Javadoc's inline tags such as {@link ...} and {@code ...}. Use [links] and Markdown backticks instead.
There is no @deprecated tag either. Use the @Deprecated annotation, which the compiler and the IDE understand:
/** Formats [cents] as dollars. */
@Deprecated(
message = "Use formatMoney(cents, \"USD\")",
replaceWith = ReplaceWith("formatMoney(cents, \"USD\")"),
)
fun formatDollars(cents: Long): String = formatMoney(cents, "USD")
/** Formats [cents] as an amount in the given ISO 4217 [currency]. */
fun formatMoney(cents: Long, currency: String): String =
"%d.%02d %s".format(cents / 100, cents % 100, currency)
fun main() {
println(formatDollars(12345))
}
dep.kt:17:13: warning: 'fun formatDollars(cents: Long): String' is deprecated. Use formatMoney(cents, "USD").
println(formatDollars(12345))
^^^^^^^^^^^^^
123.45 USD
IntelliJ IDEA offers a quick fix that rewrites the call using ReplaceWith.
Links
Square brackets link to a declaration. Names are resolved like code in the same file, so imports apply:
package com.example.stack
/**
* Link forms:
* - a class: [BoundedStack]
* - a member: [BoundedStack.push]
* - a parameter: [stack]
* - an extension: [pushAll]
* - custom text: [the push function][BoundedStack.push]
* - fully qualified: [kotlin.collections.ArrayDeque]
* - JDK class: [java.time.Instant]
*/
fun <T> describe(stack: BoundedStack<T>): String = "size=${stack.size}"
Dokka turned every link above into a hyperlink: local declarations to pages in the generated docs, ArrayDeque to kotlinlang.org and Instant to the JDK docs on docs.oracle.com.
A link to a name that doesn't exist is rendered as plain text, and Dokka prints a warning:
WARN: Couldn't resolve link: [popAll] in BoundedStack.kt/com.example.stack.BoundedStack.peek (stack/main)
IntelliJ IDEA resolves KDoc links as well. Ctrl+click works on them, and renaming a declaration updates the links that point to it. That is a good reason to prefer [push] over a plain `push`.
Markdown
KDoc text is Markdown: **bold**, *italic*, `code`, lists, headings, [text](https://url) links and fenced code blocks. Code blocks are not compiled or checked. Code that must stay correct belongs in a @sample.
Samples
@sample takes the fully qualified name of a function. Dokka copies the function's body into the docs. The sample is ordinary Kotlin, so you can compile it, run it or call it from a test:
package com.example.stack.samples
import com.example.stack.BoundedStack
fun undoHistory() {
val undo = BoundedStack<String>(capacity = 3)
for (edit in listOf("type a", "type b", "bold", "delete")) {
undo.push(edit)
}
println(undo.pop()) // delete
println(undo.size) // 2
}
fun main() {
undoHistory()
}
Output:
delete
2
The Kotlin standard library documents most functions this way.
Module and package documentation
A package can't have a KDoc comment in source. Package and module docs go in a Markdown file with # Module and # Package headings:
# Module stack
Small collection types for undo history and caches.
# Package com.example.stack
Stacks with a fixed maximum size.
Dokka reads this file through the includes setting shown below. The module text appears on the start page, the package text on the package page.
Generating docs with Dokka
Dokka is the documentation engine for Kotlin, like Javadoc for Java. It understands KDoc and Javadoc comments, and mixed Kotlin/Java projects. It can output HTML (the default) or Javadoc-style HTML.
Gradle
build.gradle.kts:
plugins {
kotlin("jvm") version "2.4.21"
id("org.jetbrains.dokka") version "2.2.0"
}
repositories {
mavenCentral()
}
dokka {
moduleName.set("stack")
dokkaPublications.html {
failOnWarning.set(true)
}
dokkaSourceSets.main {
includes.from("Module.md")
samples.from("src/samples/kotlin")
reportUndocumented.set(true)
sourceLink {
localDirectory.set(file("src/main/kotlin"))
remoteUrl("https://github.com/example/stack/tree/main/src/main/kotlin")
remoteLineSuffix.set("#L")
}
}
}
What the settings do:
includesadds the module and package Markdown filesampleslists directories that hold@samplefunctions; they don't have to be part of the compiled source setreportUndocumentedwarns about public declarations without KDocsourceLinkadds a "source" link from every declaration to the line on GitHubfailOnWarningfails the build on any warning, including unresolved links. Turn it on in CI to keep the docs from rotting
Run:
$ ./gradlew dokkaGenerate
w: [:dokkaGeneratePublicationHtml] Undocumented: com.example.stack/BoundedStack/clear/#/ (jvm)
> Task :dokkaGeneratePublicationHtml
> Task :dokkaGenerate
With failOnWarning set, the build stops on that warning:
Execution failed for task ':dokkaGeneratePublicationHtml'
> Failed with warningCount=1 and errorCount=0
Document clear() or hide it with @suppress. The site is written to build/dokka/html/. Open index.html in a browser, or publish the directory to GitHub Pages.
This is the Dokka 2 Gradle plugin (dokka { } block, dokkaGenerate task). The Dokka 1 tasks (dokkaHtml, dokkaJavadoc) and the tasks.dokkaHtml { } configuration are deprecated.
Javadoc JAR for Maven Central
Maven Central requires a -javadoc.jar next to every published library. Add the Javadoc format plugin and package its output:
plugins {
kotlin("jvm") version "2.4.21"
id("org.jetbrains.dokka") version "2.2.0"
id("org.jetbrains.dokka-javadoc") version "2.2.0"
}
val dokkaJavadocJar by tasks.registering(Jar::class) {
from(tasks.dokkaGeneratePublicationJavadoc.flatMap { it.outputDirectory })
archiveClassifier.set("javadoc")
}
./gradlew dokkaJavadocJar creates build/libs/stack-javadoc.jar. Attach it to your Maven publication with artifact(dokkaJavadocJar).
Command line
Without Gradle, use the Dokka CLI. Download dokka-cli, dokka-base and analysis-kotlin-symbols (version 2.2.0) plus kotlinx-html-jvm and freemarker from Maven Central, and describe the project in a JSON file:
{
"moduleName": "stack",
"outputDir": "out",
"pluginsClasspath": [
"jars/dokka-base-2.2.0.jar",
"jars/analysis-kotlin-symbols-2.2.0.jar",
"jars/kotlinx-html-jvm-0.11.0.jar",
"jars/freemarker-2.3.34.jar"
],
"sourceSets": [{
"sourceSetID": { "scopeId": "stack", "sourceSetName": "main" },
"sourceRoots": ["src"],
"samples": ["samples"],
"includes": ["Module.md"],
"classpath": ["kotlinc/lib/kotlin-stdlib.jar"],
"reportUndocumented": true,
"analysisPlatform": "jvm"
}]
}
$ java -jar jars/dokka-cli-2.2.0.jar dokka.json
...
WARN: Undocumented: com.example.stack/BoundedStack/clear/#/ (JVM)
...
Generation completed with 1 warning and 0 errors
Put the standard library and your dependencies on classpath. Without it, links to library types such as [NoSuchElementException] can't be resolved and produce warnings.
What to write in comments
KDoc describes the contract: what a declaration does, what its parameters mean, what it returns and throws, and things like thread safety or performance that the signature doesn't show. Callers read KDoc without reading the body.
Regular comments in a function body explain why code is written the way it is. Don't narrate what the code does:
// Bad: repeats the code
i++ // increment i
// Good: explains a decision a reader would question
// The API returns 404 for an empty cart instead of an empty list.
val items = try { api.cartItems(id) } catch (e: NotFoundException) { emptyList() }
Other guidelines:
- Start a KDoc summary with a verb in the third person ("Returns...", "Pushes..."), as the standard library does.
- Keep
TODOcomments short and searchable. IntelliJ IDEA listsTODOandFIXMEcomments in the TODO tool window. The standardTODO("reason")function is different: it compiles, and throwsNotImplementedErrorwhen called. - Delete commented-out code instead of keeping it. Version control remembers it.
- Prefer clearer names, named arguments and types over comments that explain unclear code.
See Coding conventions for formatting rules and for running ktlint.