0
0
Kotlinprogramming~15 mins

Comments and documentation syntax in Kotlin - Deep Dive

Choose your learning style9 modes available
Overview - Comments and documentation syntax
What is it?
Comments in Kotlin are notes written inside the code that the computer ignores when running the program. They help programmers explain what the code does or why certain choices were made. Documentation syntax is a special way to write comments that tools can use to create helpful guides for others. Together, they make code easier to understand and maintain.
Why it matters
Without comments and documentation, code can become confusing and hard to fix or improve, especially when many people work on it or when returning to it after a long time. They prevent misunderstandings and save time by clearly explaining the purpose and details of the code. This helps teams work better and reduces bugs caused by wrong assumptions.
Where it fits
Before learning comments, you should know basic Kotlin syntax like variables and functions. After mastering comments and documentation, you can learn about code style, testing, and tools that generate documentation automatically.
Mental Model
Core Idea
Comments are invisible notes in code that explain its meaning, and documentation syntax is a special comment style that creates helpful guides automatically.
Think of it like...
Comments are like sticky notes you put on a recipe to remind yourself why you added a pinch of salt, while documentation syntax is like writing a clear recipe card that others can read and follow easily.
┌───────────────┐
│ Kotlin Code   │
│ ┌───────────┐ │
│ │ // Comment│ │  <-- Human reads this note
│ └───────────┘ │
│ ┌───────────┐ │
│ │ /** Doc  │ │  <-- Tools use this to build docs
│ │  * Info   │ │
│ └───────────┘ │
└───────────────┘
Build-Up - 7 Steps
1
FoundationSingle-line comments basics
🤔
Concept: Learn how to write simple comments that explain one line or idea in the code.
In Kotlin, you write a single-line comment by starting the line with two slashes `//`. Everything after `//` on that line is ignored by the computer. Example: val age = 25 // This stores the user's age This comment helps anyone reading the code understand what `age` means.
Result
The program runs normally, but humans see the comment to understand the code better.
Understanding single-line comments is the first step to making your code clearer without changing how it works.
2
FoundationMulti-line comments basics
🤔
Concept: Learn how to write comments that span several lines to explain bigger ideas or temporarily disable code.
Kotlin uses `/*` to start and `*/` to end a multi-line comment. Everything between these symbols is ignored. Example: /* This function calculates the total price. It adds tax and discounts. */ fun calculatePrice() { ... } You can also use multi-line comments to comment out code during testing.
Result
Long explanations or blocks of code can be hidden from the computer but visible to humans.
Multi-line comments let you explain complex parts or pause code without deleting it, which helps during development.
3
IntermediateKDoc documentation syntax
🤔Before reading on: do you think KDoc comments are just regular comments or do they have special rules? Commit to your answer.
Concept: KDoc is a special comment style in Kotlin used to write documentation that tools can process to create readable guides.
KDoc comments start with `/**` and end with `*/`. Inside, you can write descriptions and special tags like `@param` and `@return` to explain functions and classes. Example: /** * Adds two numbers. * @param a first number * @param b second number * @return sum of a and b */ fun add(a: Int, b: Int): Int = a + b Tools like Dokka can turn these comments into HTML documentation.
Result
Your code is not only explained for humans reading the source but also can generate professional documentation automatically.
Knowing KDoc syntax unlocks the power of automatic documentation, saving time and improving code sharing.
4
IntermediateUsing tags in KDoc comments
🤔Before reading on: do you think tags like @param are optional or required in KDoc? Commit to your answer.
Concept: Tags in KDoc provide structured information about code elements like parameters, return values, and exceptions.
Common KDoc tags include: - `@param` to describe function parameters - `@return` to describe what a function returns - `@throws` to describe exceptions thrown Example: /** * Divides two numbers. * @param numerator the top number * @param denominator the bottom number * @return the division result * @throws ArithmeticException if denominator is zero */ fun divide(numerator: Int, denominator: Int): Int { if (denominator == 0) throw ArithmeticException("Cannot divide by zero") return numerator / denominator } These tags help tools and readers understand the code clearly.
Result
Documentation becomes more precise and useful, helping prevent misuse of functions.
Using tags consistently makes your documentation trustworthy and easy to navigate.
5
IntermediateCommenting best practices
🤔
Concept: Learn how to write comments that are helpful, clear, and maintainable.
Good comments: - Explain why, not what (the code shows what) - Are kept up to date with code changes - Avoid obvious or redundant information - Use proper grammar and spelling Example bad comment: val x = 5 // sets x to 5 Better comment: // Maximum number of retries allowed val maxRetries = 5 This helps future readers understand intent, not just code.
Result
Your comments become valuable guides rather than noise.
Knowing what to comment and how improves communication and reduces confusion in teams.
6
AdvancedNested and disabled comments
🤔Before reading on: do you think Kotlin allows comments inside comments? Commit to your answer.
Concept: Kotlin supports nested multi-line comments, which lets you disable code blocks that already contain comments safely.
You can put `/* ... */` inside another `/* ... */` comment. Example: /* fun test() { /* This is a nested comment */ println("Hello") } */ This is useful when you want to comment out code that already has comments without breaking it.
Result
You can safely disable complex code blocks without removing inner comments.
Understanding nested comments prevents syntax errors during debugging or testing.
7
ExpertKDoc integration with tools and IDEs
🤔Before reading on: do you think KDoc comments affect code execution or only help developers? Commit to your answer.
Concept: KDoc comments integrate deeply with Kotlin tools and IDEs to provide features like code completion, quick info, and documentation generation.
IDEs like IntelliJ IDEA use KDoc to show helpful hints when you hover over functions or classes. Tools like Dokka generate HTML or Markdown documentation from KDoc comments. This integration means writing good KDoc improves both developer experience and project documentation quality. Example: Hovering over a function shows its KDoc summary and parameter info instantly.
Result
Developers get faster, clearer information while coding, and projects have professional docs automatically.
Knowing how KDoc works with tools helps you write comments that maximize productivity and code quality.
Under the Hood
Comments are ignored by the Kotlin compiler during code translation, so they do not affect the program's behavior or performance. KDoc comments are parsed by documentation tools like Dokka, which read the special tags and text to generate formatted documentation files. IDEs parse KDoc to provide inline help and code completion by linking comments to code elements.
Why designed this way?
Kotlin adopted KDoc based on Java's Javadoc to leverage existing documentation standards and tools, making it easier for developers to write and maintain documentation. Nested comments were included to allow safe commenting out of code blocks containing comments, a common need during debugging. The design balances human readability with tool automation.
┌───────────────┐
│ Kotlin Source │
│ ┌───────────┐ │
│ │ Code      │ │
│ │ /* Comment│ │  <-- Compiler ignores
│ │  */       │ │
│ └───────────┘ │
│               │
│ ┌───────────┐ │
│ │ KDoc      │ │  <-- Tools parse
│ │ /** ... */│ │
│ └───────────┘ │
└───────┬───────┘
        │
        ▼
┌───────────────┐
│ Documentation │
│ Generator     │
│ (Dokka)       │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do you think comments slow down your Kotlin program when it runs? Commit to yes or no.
Common Belief:Comments make the program slower because they add extra text.
Tap to reveal reality
Reality:Comments are completely ignored by the compiler and do not affect runtime speed or program size.
Why it matters:Believing comments slow down code might discourage writing helpful explanations, making code harder to maintain.
Quick: Do you think KDoc comments are required for Kotlin code to compile? Commit to yes or no.
Common Belief:KDoc comments are mandatory for Kotlin code to work properly.
Tap to reveal reality
Reality:KDoc comments are optional and only used for documentation; the code runs fine without them.
Why it matters:Misunderstanding this can cause unnecessary effort or confusion about code errors.
Quick: Can you nest single-line comments inside multi-line comments in Kotlin? Commit to yes or no.
Common Belief:You can nest any type of comment inside another comment freely.
Tap to reveal reality
Reality:Only multi-line comments can be nested; single-line comments inside multi-line comments are treated as normal text.
Why it matters:Incorrect nesting can cause syntax errors or unexpected code behavior during commenting out code.
Quick: Do you think writing comments that explain what the code does is always best? Commit to yes or no.
Common Belief:Comments should always describe what the code does line by line.
Tap to reveal reality
Reality:Good comments explain why the code does something or important context, not just what is obvious from the code itself.
Why it matters:Over-commenting obvious code clutters files and wastes time; under-commenting important decisions causes confusion.
Expert Zone
1
KDoc supports linking to other code elements using square brackets, enabling cross-references in documentation.
2
Nested multi-line comments can be used creatively to toggle code sections during development without removing inner comments.
3
KDoc tags can be extended with custom tags in Dokka to support project-specific documentation needs.
When NOT to use
Avoid excessive commenting in very simple or self-explanatory code; instead, write clear code. For documentation, if the project is very small or experimental, lightweight comments may suffice without full KDoc. Use external documentation tools or README files for broader explanations instead of cluttering code.
Production Patterns
In professional Kotlin projects, KDoc is used extensively for public APIs to generate user-friendly documentation websites. Teams enforce comment quality via code reviews and automated tools that check for missing or malformed KDoc tags. Nested comments help during debugging complex features by safely disabling code blocks.
Connections
Code readability
Comments and documentation directly improve code readability by explaining intent and usage.
Understanding how to write effective comments is a key skill to make code accessible and maintainable for others.
Technical writing
KDoc is a form of technical writing embedded in code, sharing principles with writing manuals or guides.
Learning KDoc helps programmers develop skills in clear, structured communication useful beyond coding.
Legal contracts
Both documentation and contracts require precise language and clear explanations to avoid misunderstandings.
Recognizing this connection highlights the importance of clarity and accuracy in code comments to prevent costly errors.
Common Pitfalls
#1Writing comments that just repeat the code without adding value.
Wrong approach:val count = 10 // sets count to 10
Correct approach:// Maximum number of retries allowed val count = 10
Root cause:Misunderstanding that comments should explain intent or context, not restate obvious code.
#2Forgetting to update comments after changing code.
Wrong approach:/** * Returns the sum of two numbers. */ fun multiply(a: Int, b: Int): Int = a * b
Correct approach:/** * Returns the product of two numbers. */ fun multiply(a: Int, b: Int): Int = a * b
Root cause:Treating comments as static text rather than living documentation that must stay accurate.
#3Using single-line comments to try to comment out large blocks of code.
Wrong approach:// val a = 1 // val b = 2 // val c = a + b
Correct approach:/* val a = 1 val b = 2 val c = a + b */
Root cause:Not knowing multi-line comments or nested comments leads to inefficient or error-prone commenting.
Key Takeaways
Comments are notes in code ignored by the computer but essential for human understanding.
KDoc is a special comment style in Kotlin that helps generate professional documentation automatically.
Good comments explain why code exists or how it should be used, not just what it does.
Kotlin supports nested multi-line comments, allowing safe disabling of code blocks with comments inside.
Writing clear, accurate comments and documentation improves teamwork, maintenance, and reduces bugs.