How to Use Comments in Kotlin (2025 Guide to Writing Clean, Readable 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
Post a Comment