← Back to Kotlin Course | Chapter 1: Setup & Basics | Lesson 7 of 7

Comments in Kotlin

Comments are little notes left inside code that the computer ignores, but that help humans understand what the code is doing.

Single-Line Comments

A double slash // marks everything after it on that line as a comment, which the compiler ignores entirely. This is the most common way to leave short notes next to code.

Example: Single-Line Comments

markup
fun main() {
    // This line prints a greeting
    println("Hello!") // greeting printed here
}

Multi-Line Block Comments

Wrapping text in /* and */ creates a block comment that can span multiple lines, useful for longer explanations. Kotlin, unlike Java, even allows these block comments to be nested inside each other.

Example: Multi-Line Block Comments

markup
fun main() {
    /*
     * This program demonstrates block comments.
     * They can span several lines.
     */
    println("Block comments explained above")
}

Documentation Comments (KDoc)

Comments starting with /** are KDoc comments, used to document functions and classes so tools can generate reference documentation automatically, similar to Javadoc in Java.

Example: Documentation Comments (KDoc)

markup
/**
 * Greets a person by name.
 */
fun greet(name: String) {
    println("Hello, $name!")
}

fun main() {
    greet("Kotlin")
}

Writing Useful Comments

The best comments explain *why* a piece of code exists or a decision was made, not what it obviously does. Comments that only restate the code add clutter without adding understanding.

Note: If you feel the need to comment *what* a line does, consider renaming variables/functions to make the code self-explanatory instead.

Example: Writing Useful Comments

markup
fun main() {
    // Using 0.5 as a discount rate agreed with the finance team
    val discountRate = 0.5
    println("Discount rate: $discountRate")
}
Common Mistakes
  1. Forgetting that // only comments out the rest of that single line, so code after it on the same line is fine but the next line still runs normally.
  2. Nesting /* */ block comments incorrectly, not realizing Kotlin actually does support nested block comments unlike Java.
  3. Writing comments that just repeat what the code already says, instead of explaining *why* it exists.
Chapter Summary
  • // starts a single-line comment that continues to the end of that line.
  • /* ... */ marks a multi-line block comment, and Kotlin allows these to be nested.
  • KDoc comments start with /** ... */ and are used to generate documentation for functions and classes.
  • Good comments explain intent and reasoning, not just restate what the code obviously does.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.