On this page
The short answerWhy Kotlin documentation examples breakClassify the block before choosing a checkCompile and run a complete programKeep KDoc samples in compiled sourceExtract standalone Markdown fences for a basic checkChoose fence labels deliberatelyPut the checks in CITriage failures with their contextWhere DocsAlive fitsPasteable checklistThe sources we checkedFAQThe short answer
Test Kotlin documentation examples with the Kotlin compiler and the JDK version your readers are expected to use. Classify each block first: a complete program, a script, a fragment and a Gradle build file need different checks. Compile complete examples, run the ones that promise behavior, keep reusable samples in a compiled source set, and record intentional gaps. Treat a failure as a documentation bug only after checking the documented setup, version and context.
Run these checks when code or documentation changes, before a release, and on a schedule if dependencies can drift. A compiler check catches broken names and types; a separate assertion or output check is needed when a page promises a particular result. For a broader workflow, see how to test documentation code and the documentation testing checklist.
DocsAlive recognizes fences labeled kotlin but skips them as not executable today. It can still check supported blocks elsewhere on the same page and help classify findings. Use Kotlin tooling in your own CI for the Kotlin checks described below.
Why Kotlin documentation examples break
Kotlin examples appear in READMEs, KDoc comments, Dokka sites, Android guides and server documentation. Their presentation differs, but each example makes a promise about a particular environment. It may rely on a compiler version, JDK, dependency, import, enclosing class or earlier step that the page does not state.
A library release can rename or remove an API while a copied example remains unchanged. A call can first produce a deprecation warning and later become an error. A page can use a helper declared at the top level as though it were a class member, or show a member call without creating the required object. Either mistake can be difficult to spot when the surrounding declarations are absent from the listing.
Imports are another common source of drift. A short example may compile in the project where it was written because the author included imports in a different file or used an IDE to add them. A reader copying only the published block does not inherit that context. Coroutine examples have an additional boundary: a suspending operation needs an appropriate scope or an entry point such as runBlocking, along with the relevant dependency. A snippet that omits both the surrounding scope and the setup is not a complete runnable program.
Build instructions can fail before Kotlin sees the source. A Gradle dependency may have the wrong group, artifact or version, or the page may target a library release that does not contain the documented API. A sample that works against a local checkout does not establish that the coordinates on the page install the same code.
As read on November 11, 2026, the Kotlin releases page listed Kotlin 2.4.21 as current and planned Kotlin 2.5.0 for December 2026. State the Kotlin and JDK versions used for a check, and distinguish a planned release from one that has shipped. The examples in this guide use Kotlin 2.4.21 and JDK 21. See the Kotlin releases page.
Classify the block before choosing a check
A fence label identifies the language; it does not tell a test whether the block is intended to stand alone. Record the role of the block and the context a reader is supposed to have.
| Block | What it represents | Useful check |
|---|---|---|
Complete program with main |
A standalone entry point, with its required imports and declarations | Compile, run and check the promised result |
Kotlin script, saved as .kts |
Statements intended for the script runner | Run with kotlinc -script |
| Fragment | Part of a larger declaration, scope or sequence | Mark it as a fragment and test it in its documented context |
| Gradle build file | Build configuration, often using Kotlin syntax | Test in a real, representative Gradle project |
| KDoc sample function | Source code whose body is included in generated docs | Compile the source set containing the function and build the docs |
| Output listing | A result shown to the reader | Compare it with a controlled run when the page promises that result |
A fragment is not necessarily wrong. A short listing can make a concept easier to see, provided the page tells readers where it belongs and supplies any necessary setup. The problem is an unmarked fragment presented as something a reader can paste into a new file and run.
Conversely, a complete program should not rely on a hidden import, local file or variable created by the author. Test it in a clean directory with the dependencies and commands the page actually documents. If the test supplies setup outside the page, record that setup so a reviewer can decide whether a reader would reasonably know to provide it.
A Gradle build file deserves its own project-level check. For instance, an illustrative dependency declaration for the fictional Acme SDK might name com.acme.sdk as a group. That name is a placeholder, not a published dependency to install. A real guide should give readers the actual coordinates and version for its own library and verify them in a build. See installation documentation testing for the full install path.
Compile and run a complete program
Save this complete standard-library program as Hello.kt:
fun main() {
println("Hello, Kotlin!")
}
Compile it into a runnable JAR and run it:
kotlinc Hello.kt -include-runtime -d hello.jar
java -jar hello.jar
The second command prints Hello, Kotlin!. The compiler command checks that the program compiles and includes the Kotlin runtime in the JAR. Running the JAR checks the entry point and behavior as well. The Kotlin command-line guide documents this workflow.
Keep these two results distinct in a report. A successful compile establishes that the compiler accepted the source under the selected environment. It does not establish that the program printed what the page claims, connected to the intended service or produced the right business result. For a stable result, a separate test can assert the value; for output that varies, state what a reviewer should inspect.
For a library example, add the documented library to a real build and use the same version readers install. Compile against the release artifact when assessing the release path. Compiling only against the current source checkout can miss a packaging or publishing mistake; compiling only against a published release can miss a breaking change being prepared in the checkout. Those are useful but different checks.
Run a script
A script can contain top-level statements without a main function. Save this as hello.kts:
println("Hello from a script!")
Run it with:
kotlinc -script hello.kts
It prints Hello from a script!. Do not silently convert every fragment into a script: script context may make a listing pass even though the page tells a reader to put it inside a class or function. Use the form the documentation prescribes, and test the enclosing code when the placement matters.
Make warnings visible
A warning is evidence of a possible future break, especially when a public API is being retired. Save the following complete program as D.kt. The call is intentionally deprecated so that the strict check fails:
@Deprecated("Use currentGreeting instead")
fun oldGreeting(): String = "Hello"
fun currentGreeting(): String = "Hello"
fun main() {
println(oldGreeting())
}
Run the strict compiler check:
kotlinc -Werror D.kt -d out
The compiler reports the deprecation warning and fails with error: warnings found and -Werror specified. Without -Werror, this particular deprecated call warns but the compilation succeeds. Use a strict check when the project intends warnings to block a change, and keep the compiler version in the result: warning behavior can change with the toolchain and dependencies.
A warning does not always mean the page is immediately unusable. Review the deprecation message, the supported library versions and the intended migration. If the API has been removed or the documented compiler treats its use as an error, a formerly working example may now prevent readers from completing the task.
Keep KDoc samples in compiled source
KDoc supports @sample with a qualified function name. Dokka can include the body of that function in generated documentation. Put the function in a source set that your build actually compiles, such as a configured test or samples source set. Then source changes, including a renamed API used in the function, can break the build rather than silently leaving a stale code fence in a comment.
The following is a small source layout. Save both declarations in a compiled source set; the qualified name in the KDoc refers to the sample function.
package guide
/**
* Produces a greeting.
*
* @sample guide.greetingSample
*/
fun greeting(name: String): String = "Hello, $name!"
fun greetingSample() {
check(greeting("Ada") == "Hello, Ada!")
}
Compilation checks the reference inside greetingSample; running that function as part of a test checks its assertion. Configure the documentation build so it can resolve the sample function as well. A source rename can fail compilation where it is used, while a change to the sample identifier or documentation configuration should also be caught by reviewing the generated docs build.
The distinction matters because Markdown fences written directly in a README or KDoc comment are not compiled by Kotlin itself. A successful application build does not prove that those listings compile. The KDoc reference describes @sample, and the Dokka introduction describes Kotlin’s documentation engine.
Consider generated samples from Markdown
kotlinx-knit is an experimental JetBrains incubator option for projects that want to generate Kotlin example files and tests from Markdown. A page can include a directive such as:
<!--- KNIT example-basic-01.kt -->
With the tool configured for the project, run gradlew knit to generate the files. The documented workflow commits generated files and verifies them on later builds. Follow the project’s instructions for setup and the placement of directives; the directive alone does not compile a page.
This approach can reduce divergence between a page and files that the build checks, but it still needs a deliberate model of dependencies, fragments and expected behavior. Review generated changes alongside the Markdown, and make sure a generated sample uses the same version and setup that the reader sees.
Extract standalone Markdown fences for a basic check
The following Python 3 script is a small starting point for a repository that uses standalone kotlin fences. It writes one .kt file per selected block to a temporary directory and invokes kotlinc for each file. A block whose first line is // fragment is skipped.
Save it as check_kotlin_fences.py:
import re
import subprocess
import sys
import tempfile
from pathlib import Path
FENCE = re.compile(
r"^```kotlin[ \t]*\r?\n(.*?)^```[ \t]*$",
re.MULTILINE | re.DOTALL,
)
def main() -> int:
if len(sys.argv) < 2:
print("Usage: python3 check_kotlin_fences.py FILE.md [FILE.md ...]")
return 2
passed = failed = skipped = 0
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
number = 0
for name in sys.argv[1:]:
path = Path(name)
try:
markdown = path.read_text(encoding="utf-8")
except (OSError, UnicodeError) as error:
print(f"Cannot read {path}: {error}")
failed += 1
continue
for match in FENCE.finditer(markdown):
number += 1
code = match.group(1)
line = markdown.count("\n", 0, match.start()) + 1
location = f"{path}:{line}"
if code.splitlines() and code.splitlines()[0].strip() == "// fragment":
print(f"SKIP {location}: fragment")
skipped += 1
continue
source = root / f"block_{number}.kt"
output = root / f"classes_{number}"
source.write_text(code, encoding="utf-8")
try:
result = subprocess.run(
["kotlinc", str(source), "-d", str(output)],
text=True,
capture_output=True,
check=False,
)
except OSError as error:
print(f"FAIL {location}: cannot start kotlinc: {error}")
failed += 1
continue
if result.returncode == 0:
print(f"PASS {location}")
passed += 1
else:
print(f"FAIL {location}")
print(result.stderr.strip())
failed += 1
print(f"Summary: {passed} passed, {failed} failed, {skipped} skipped")
return 1 if failed else 0
if __name__ == "__main__":
raise SystemExit(main())
Run it from a directory where kotlinc is on PATH:
python3 check_kotlin_fences.py README.md
This is a compile check, not a complete Markdown parser or a runnable-example harness. It handles simple triple-backtick fences at the start of a line; it does not handle nested fences, alternate fence lengths, indented fences, tabs, .kts scripts or build-file semantics. It does not install dependencies, preserve page state, run main, compare output or verify that a fragment is valid in its surrounding program. A missing file or compiler produces a failed summary rather than a false pass.
Each block receives a separate compiler process. That makes the example easy to understand, but JVM startup takes several seconds per file. For a larger suite, batch compatible files into a compilation where possible, while keeping separate compilations for examples that intentionally reuse names or require different dependencies. If a batch fails, retain enough location information to identify the source block.
The explicit fragment marker is a convention for this script, not proof that the omitted code works. Maintain a separate integration test for important fragments, particularly coroutine examples and multi-step pages. A reader should still be able to find the scope, imports and dependency needed to use the fragment.
Choose fence labels deliberately
Label Kotlin source fences kotlin. In DocsAlive today, that label is recognized and the block is skipped with the reason not executable (kotlin) and category not-executable. That is a visible coverage gap, not a compiler result.
The labels kt and kts are not in its language map. In the current engine, such a block can appear as a pass even though nothing was compiled or run. Read that result as unchecked, and prefer kotlin for a truthful skip. The file suffix for a script can still be .kts; the Markdown fence label and the file name serve different purposes. Keep your own script or build check responsible for the actual compilation.
Put the checks in CI
The following GitHub Actions outline checks out the repository, sets up JDK 21, downloads the specified Kotlin compiler and runs the fence script. Commit check_kotlin_fences.py at the repository root, or adjust the final command for its location. The repository must contain README.md.
name: Kotlin documentation
on:
pull_request:
push:
jobs:
kotlin-docs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-java@v6
with:
distribution: temurin
java-version: '21'
- name: Install Kotlin compiler
run: |
curl -fsSLo kotlin-compiler.zip https://github.com/JetBrains/kotlin/releases/download/v2.4.21/kotlin-compiler-2.4.21.zip
unzip -q kotlin-compiler.zip
echo "$PWD/kotlinc/bin" >> "$GITHUB_PATH"
- name: Compile standalone README blocks
run: python3 check_kotlin_fences.py README.md
This job checks the subset selected by the script. Add project builds for KDoc samples, real dependency coordinates and Gradle configuration; add explicit execution or assertions for promised behavior. A YAML fence is configuration for the CI service, not evidence that a Kotlin compiler has checked it.
Run relevant checks on pull requests and the release candidate. A scheduled run can detect dependency drift, and a post-release check against the published artifact can verify the reader’s installation path. Record whether each result used a checkout, a release candidate or a published package. The GitHub Actions documentation testing guide covers organizing these checks.
Triage failures with their context
A compiler error is useful evidence, but the next action depends on what the page promised. Preserve the compiler version, dependency versions, command, page and line with the result.
| Finding | Likely interpretation | Next action |
|---|---|---|
| Unresolved name in a complete example | A missing import, removed API or incorrect declaration may make the page unusable | Reproduce with the documented dependencies and fix the page or code |
| Missing coroutine scope in a block presented as complete | The reader lacks context required for the call | Supply and test a complete entry point or identify the enclosing scope |
| Fragment fails alone | The block may intentionally depend on surrounding code | Check the full documented context and mark the fragment |
| Dependency cannot be resolved | Coordinates, version, repository or network may be at fault | Verify the published artifact and the reader’s install instructions |
| Deprecation warning | The example may work now but require migration | Review the supported versions and decide whether strict warnings should block |
| Wrong output after a successful run | Compilation passed, but the behavioral promise may be stale | Reproduce and update the assertion, example or stated result |
| Missing credential or fixture | The run lacks something the page assumes | Record the gap and decide whether the prerequisite is adequately documented |
| Compiler or JDK mismatch | The test may not reflect the supported environment | Repeat with the stated versions and correct the version guidance if needed |
Avoid “fixing” a missing import solely in test setup if readers must add it themselves. The same principle applies to Gradle configuration and coroutine setup: a test harness should make its additions visible. For a fictional placeholder such as the Acme SDK, do not report failure to install the placeholder as proof that a real package is broken.
Where DocsAlive fits
DocsAlive extracts fenced blocks and records page and line information, then plans, runs or skips blocks according to its supported languages. It keeps supported examples in page order and uses a fresh container per page. Its triage distinguishes likely documentation bugs from cases such as missing context, credentials, fixtures and unsupported tooling. See framework support and findings.
Kotlin is not executed by the product today. Pair its report with the compiler, Gradle and sample checks above, and read skipped or unchecked blocks as coverage gaps. Other supported blocks on a page can still be checked. Printed output is compared only for Python pycon or python-repl sessions; a separate output block is skipped and its contents are not compared.
A scan without --execute extracts and plans rather than executing supported blocks. A scan with --execute does not change the Kotlin limitation. Review the resulting categories and evidence before deciding which failures reflect the documentation, and use a separate project check for Kotlin behavior.
Pasteable checklist
Copy this into a pull request or release checklist:
- [ ] State the tested Kotlin, JDK and library versions.
- [ ] Identify complete programs, scripts, fragments and Gradle build files.
- [ ] Label Kotlin fences
kotlinand mark intentional fragments. - [ ] Compile complete examples with their documented imports and dependencies.
- [ ] Run programs and scripts that promise behavior; check stable results.
- [ ] Test coroutine examples with the documented scope and dependency.
- [ ] Verify real Gradle coordinates and versions in a clean project.
- [ ] Compile KDoc sample functions and build the generated documentation.
- [ ] Decide whether warnings should fail the documentation build.
- [ ] Record skipped blocks, credentials, fixtures and version constraints.
- [ ] Check the release artifact and, when practical, the published install path.
- [ ] Review errors as documentation bugs, environment issues or intentional context.
The sources we checked
These sources were read on November 11, 2026.
| Source | What it covers |
|---|---|
| Kotlin command-line compiler | Compiling a runnable JAR and running scripts |
| Kotlin releases | Release types, current version and planned release |
| KDoc | Documentation comments and @sample |
| Dokka introduction | Kotlin documentation generation |
| kotlinx-knit | Experimental generation of examples and tests from Markdown |
| actions/checkout and actions/setup-java | CI checkout and JDK setup |
| Findings | Product reporting and triage context |
FAQ
Does Kotlin compile code fences in a README?
No. Kotlin does not compile Markdown fences merely because they appear in a README or KDoc comment. Extract standalone examples or keep important samples in source files that your build compiles.
What should a Kotlin documentation check run?
Compile complete programs, run scripts in script mode, and test fragments in their stated context. Use a real build for dependencies and Gradle configuration, and check promised behavior separately from compilation.
Should deprecation warnings fail the build?
That is a project policy. The compiler's -Werror option can make warnings fail a check. Review the supported versions and migration guidance so a warning is interpreted in the context readers actually use.
Can a KDoc sample catch API drift?
Yes, when the referenced sample function lives in a source set the build compiles and uses the API being documented. Build the documentation as well so problems resolving or presenting the sample are visible.
Does a Kotlin pass in DocsAlive mean the code compiled?
No. Kotlin fences labeled kotlin are skipped as not executable. The unmapped kt and kts labels can appear as passes without a check, so use kotlin and run a separate compiler check.
How should coroutine fragments be tested?
Put important fragments in a test with the required dependency and a valid scope or entry point. Make that context visible in the documentation when a reader needs it to use the code.




