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. 🔍
..

Post a Comment

Previous Post Next Post