Comments in Kotlin

1. Why Comments Are Important

Comments are notes in your code that are ignored by the compiler. They help developers:

2. How to Use Comments in Kotlin

2.1 Single-Line Comments

Start with // and extend to the end of the line.

// This is a single-line comment
val name = "Kotlin" // Comment can also follow code

2.2 Multi-Line Comments

Enclosed between /* and */, can span multiple lines.

/* This is a multi-line comment
   which spans several lines */
val age = 25

2.3 Nested Multi-Line Comments

Kotlin allows nested comments:

/* Outer comment
   /* Inner comment */
   Outer comment ends */

2.4 Documentation Comments

Use /** ... */ to generate API documentation. Place them above classes, functions, or properties.

/**
 * Adds two numbers and returns the result.
 * @param a First number
 * @param b Second number
 * @return Sum of a and b
 */
fun add(a: Int, b: Int): Int {
    return a + b
}

2.5 Best Practices

3. Example Program

fun main() {
    // Greeting program with comments
    
    val name = "Alice"  // User's name
    val age = 28        // User's age

    /* Print a greeting using string templates */
    println("Hello, $name! You are $age years old.")
    
    /**
     * Function to double a number.
     * @param x Number to double
     * @return Double the input
     */
    fun double(x: Int) = x * 2

    println("Double of age: ${double(age)}")
}

Output:

Hello, Alice! You are 28 years old.
Double of age: 56

4. Common Interview Questions

Why Comments?

How Comments Work?

Other Interview Questions