How to Use Comments in Kotlin (2025 Guide to Writing Clean, Readable Code)

Comments in Kotlin: Your Secret Weapon for Clear, Readable Code! ✍️ They explain logic, enhance collaboration, and let you experiment by disabling code. ๐Ÿ› ️

Single-line Comments ๐Ÿš€

Single-line comments start with //—quick, clean, and perfect for short notes or toggling code! ๐ŸŒŸ

Kotlin ignores everything after // until the line ends, making it ideal for explanations or debugging. ๐Ÿง‘‍๐Ÿ’ป

Example: Add notes or skip execution:


fun main() {
    // ๐ŸŒŸ Prints a welcome message
    println("Hello, World!") // Outputs: Hello, World! ๐Ÿ“Š
    // println("Skipped!") // ๐Ÿ›‘ Temporarily disabled
}
  • ๐Ÿ“ Clarify Intent: Explain what the code does. ๐Ÿง 
  • ๐Ÿ› ️ Debug Easily: Comment out lines to test behavior. ๐Ÿ”
  • Zero Overhead: No impact on compiled code! ๐Ÿš€


Multi-line Comments ๐Ÿ“š

Multi-line comments, enclosed in /* */, let you write detailed notes or disable code blocks. ๐Ÿ“–

All text between /* and */ is ignored, great for longer explanations or temporary code exclusion. ๐Ÿ›‘

Example: Document or pause multiple lines:


fun main() {
    /* ๐ŸŒˆ Initializes the app and sets the theme
       This is a critical setup step! */
    println("App Started!") // Outputs: App Started! ๐Ÿ“Š
    /* println("Debug info")
       println("More debug") // ๐Ÿ›‘ Disabled for now */
}
  • ๐Ÿ“– Detailed Notes: Explain complex logic or context. ๐Ÿง 
  • ๐Ÿ”ง Block Testing: Disable chunks of code during experiments. ๐Ÿ› ️
  • ๐Ÿšซ No Nesting: Multi-line comments can’t be nested in Kotlin. ⚠️


KDoc Comments: Professional Documentation with Dokka ๐Ÿ“œ

KDoc, using /** */, is Kotlin’s answer to Javadoc, perfect for documenting functions, classes, and properties. ๐ŸŒŸ

Type /** above a declaration in IntelliJ and press Enter to auto-generate a template. Pair with Dokka to create HTML, Markdown, or Javadoc-style docs! ๐Ÿ“š

Example: Document a function:


/**
 * Calculates the square of a number. ๐Ÿงฎ
 * @param number The input number to square
 * @return The squared value as a Double
 * @throws IllegalArgumentException if the input is invalid
 */
fun square(number: Double): Double {
    if (number.isNaN()) throw IllegalArgumentException("Invalid input") // ๐Ÿšซ
    return number * number // ๐ŸŒŸ
}

fun main() {
    println(square(5.0)) // Outputs: 25.0 ๐Ÿ“Š
}

Setting Up Dokka:

Step 1: Add Dokka to Project

In your project-level build.gradle:


// ๐ŸŒŸ Top-level build.gradle
plugins {
    id "org.jetbrains.dokka" version "1.9.20" apply false
}
repositories {
    mavenCentral()
}

Step 2: Configure Module

In your module-level build.gradle:


// ๐Ÿ“š Module-level build.gradle
plugins {
    id "org.jetbrains.dokka"
}
dokkaHtml {
    outputDirectory.set(file("$buildDir/dokka/html")) // ๐Ÿ“‚ Output path
    moduleName.set("MyKotlinApp") // ๐ŸŒŸ Project name
    dokkaSourceSets {
        named("main") {
            includeNonPublic.set(false) // ๐Ÿ”’ Exclude private items
            skipDeprecated.set(true) // ๐Ÿšซ Skip deprecated code
        }
    }
}

Step 3: Generate Docs

Run from the project root:


./gradlew dokkaHtml // ๐Ÿš€ Generates HTML docs

Check build/dokka/html/index.html for your polished documentation! ๐ŸŒ

  • ๐Ÿ“š KDoc Tags: Use @param, @return, @throws, @since, @see. ๐Ÿท️
  • Markdown Support: Add `code`, *italics*, or **bold** in KDoc. ๐ŸŽจ
  • ๐ŸŒŸ Dokka Power: Outputs HTML, Markdown, or Javadoc for Kotlin and mixed Java projects. ๐Ÿ“–


Nested Comments Workaround ๐Ÿ”„

Kotlin doesn’t support nested multi-line comments, but you can combine // and /* */ for similar effects. ๐Ÿ› ️

Example: Comment out a block with internal comments:


fun main() {
    /* ๐ŸŒˆ Main logic
    // println("Inner comment") // ๐Ÿ›‘ Nested single-line
    println("Active code") // Outputs: Active code ๐Ÿ“Š
    */
}
  • ๐Ÿ”ง Mix and Match: Use // inside /* */ for nested-like commenting. ๐Ÿงฉ
  • ⚠️ Avoid Complexity: Keep nesting minimal to maintain readability. ๐Ÿ“–


Special Comments: TODO, FIXME, and More ๐Ÿ“Œ

Special comments like TODO or FIXME flag tasks or issues, often highlighted by IDEs like IntelliJ. ๐Ÿ› ️

Example: Mark tasks or reminders:


fun main() {
    // TODO: Add user authentication ๐Ÿšง
    println("Basic login") // Outputs: Basic login ๐Ÿ“Š
    // FIXME: Handle edge case for empty input ๐Ÿ›‘
}
  • ๐Ÿ“Œ TODO: Marks future tasks or enhancements. ๐Ÿš€
  • ๐Ÿ›‘ FIXME: Highlights bugs or issues to resolve. ๐Ÿ”ง
  • ๐ŸŒŸ IDE Support: IntelliJ lists TODOs in a dedicated panel. ๐Ÿง‘‍๐Ÿ’ป


Version Control Annotations ๐Ÿ“…

Use comments to annotate changes for Git or other version control systems. ๐Ÿ“œ

Example: Track changes or authors:


fun main() {
    // ๐Ÿ“… Added 2025-05-10 by Alice: Improved performance
    println("Optimized code") // Outputs: Optimized code ๐Ÿ“Š
    // ๐Ÿง‘‍๐Ÿ’ป Author: Bob, 2025-05-11: Fixed null issue
}
  • ๐Ÿ“… Track History: Note dates, authors, or change reasons. ๐Ÿ•ฐ️
  • ๐Ÿค Team Clarity: Helps collaborators understand updates. ๐Ÿ‘ฅ


Commenting for Debugging and Testing ๐Ÿž

Comments are your debugging allies—disable code to isolate issues or test alternatives! ๐Ÿ”

Example: Test by commenting out code:


fun main() {
    // ๐ŸŒŸ Calculate total
    val total = 10 + 20
    println(total) // Outputs: 30 ๐Ÿ“Š
    // println(total * 2) // ๐Ÿ›‘ Testing without doubling
}
  • ๐Ÿ” Isolate Issues: Comment out suspect lines to find bugs. ๐Ÿž
  • ๐Ÿ› ️ Experiment: Toggle code to compare outcomes. ⚖️


IDE Shortcuts for Commenting ⚡

Speed up commenting with IntelliJ or Android Studio shortcuts (Windows/Linux): ๐Ÿง‘‍๐Ÿ’ป

  • ๐ŸŽฏ Line Comment: Ctrl + / toggles //. ๐Ÿš€
  • ๐Ÿ“ฆ Block Comment: Ctrl + Shift + / adds /* */. ๐Ÿ“š
  • ๐Ÿ“ KDoc: Type /** + Enter above a declaration. ๐ŸŒŸ
  • ๐Ÿ”„ Remove Comments: Use the same shortcuts to uncomment. ๐Ÿงน

Mac Tip: Replace Ctrl with Cmd. ๐ŸŽ



Best Practices for Commenting ๐ŸŒŸ

Write comments that shine with clarity and purpose! ✨

  • ๐Ÿงน Be Concise: Clear, brief comments over verbose ones. ๐Ÿ“
  • ๐Ÿ” Explain Why: Focus on intent, not just what the code does. ๐Ÿง 
  • ๐Ÿ“… Stay Current: Update comments when code changes. ๐Ÿ•ฐ️
  • ๐Ÿšซ Avoid Redundancy: Skip obvious comments (e.g., // Set x to 5). ๐Ÿ™…‍♂️
  • ๐ŸŒŸ Use KDoc for APIs: Document public functions and classes. ๐Ÿ“š
  • ๐Ÿ“Œ Leverage TODOs: Mark tasks for future work. ๐Ÿšง

Example: Good vs. Bad Comments


fun main() {
    // ๐ŸŒŸ Good: Explains purpose
    // Converts Celsius to Fahrenheit for weather app
    val tempF = tempC * 9/5 + 32
    println(tempF) // Outputs: 32 (if tempC = 0) ๐Ÿ“Š
    
    // ๐Ÿšซ Bad: Redundant
    // Variable tempF
    val tempF2 = tempC * 9/5 + 32
}


Frequently Asked Questions (FAQ) ❓

Answers to common questions about Kotlin comments! ๐Ÿง 

  • What’s the difference between // and /* */? ๐Ÿค”
    // is for single-line comments; /* */ handles multiple lines or blocks. Use // for quick notes, /* */ for longer explanations. ๐Ÿš€๐Ÿ“š
  • Can I nest multi-line comments? ๐Ÿšซ
    No, Kotlin doesn’t support nested /* */. Use // inside /* */ for similar effects. ๐Ÿ”ง
  • What is KDoc used for? ๐Ÿ“œ
    KDoc (/** */) creates structured documentation for functions, classes, and properties, often paired with Dokka for HTML or Markdown output. ๐ŸŒŸ
  • How do I generate docs with Dokka? ๐ŸŒ
    Add Dokka to your Gradle build, write KDoc, and run ./gradlew dokkaHtml to create documentation in build/dokka/html. ๐Ÿ“š
  • Are comments bad for performance? ⚡
    No, comments are ignored during compilation and have zero runtime impact. ๐Ÿš€
  • How can comments help debugging? ๐Ÿž
    Comment out code to isolate issues or test alternatives without deleting lines. ๐Ÿ”
..

Comments

Popular posts from this blog

Creating Beautiful Card UI in Flutter

Master Web Development with Web School Offline

Jetpack Compose - Card View