KOTLIN Tutorial



COMMENTS IN KOTLIN


πŸ“ Comments in Kotlin

Comments are used to explain code or to prevent execution. Kotlin supports both single-line and multi-line comments. Let’s look at them interactively!


1. Single-line Comments //

This type is great for short notes or disabling a specific line.

fun main() {
    val name = "Kotlin" // Storing language name
    println(name) // Print the value
}
  
βœ… Tip: Use single-line comments to describe logic above or beside specific lines of code.

2. Multi-line Comments /* ... */

Perfect for explaining blocks of code or temporarily disabling chunks during testing.

fun main() {
    /* This block initializes a greeting message,
       and then prints it to the console */
    val message = "Hello from Kotlin!"
    println(message)
}
  
⚠️ Warning: Don't forget to close */ or your entire program may be commented out by accident!

3. Nested Multi-line Comments βœ…

Unlike Java, Kotlin supports nesting of multi-line comments. This helps when debugging larger sections.

fun main() {
    /* Outer comment starts
       println("This line is commented")

       /* Inner nested comment */
       val x = 10
    */
    println("Only this will print!")
}
  
πŸ” Did you know? Kotlin is smart enough to handle nested comments, making it safer during debugging!

4. Best Practices πŸ’‘

  • βœ… Keep comments meaningful and concise.
  • βœ… Use comments to explain why, not just what.
  • 🚫 Avoid stating the obvious:
    val name = "John" // Assign "John" to name ← (not useful!)
          
  • βœ… Instead, explain the logic:
    val discount = price * 0.1 // 10% discount for returning users
          

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review