0
0
Kotlinprogramming~5 mins

Comments and documentation syntax in Kotlin

Choose your learning style9 modes available
Introduction

Comments help explain your code so others (and you) can understand it later. Documentation comments create helpful guides for your code.

To explain why a piece of code does something special.
To leave notes for yourself about what to fix or improve later.
To describe what a function or class does for other programmers.
To temporarily disable a line of code without deleting it.
To generate automatic documentation from your code.
Syntax
Kotlin
// This is a single-line comment
/* This is a
   multi-line comment */
/**
 * This is a documentation comment.
 * It is used to describe classes, functions, or properties.
 */

Single-line comments start with // and go to the end of the line.

Multi-line comments start with /* and end with */. They can span many lines.

Examples
This comment explains the next line of code.
Kotlin
// This is a single-line comment
val x = 5
This comment spans two lines and explains the code below.
Kotlin
/* This is a
   multi-line comment */
val y = 10
This is a documentation comment describing the add function. It helps generate documentation automatically.
Kotlin
/**
 * 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
}
Sample Program

This program uses comments to explain what the code does. The documentation comment describes the add function, and single-line comments explain lines inside the code.

Kotlin
// This program adds two numbers

/**
 * Adds two integers and returns the sum.
 *
 * @param a first integer
 * @param b second integer
 * @return sum of a and b
 */
fun add(a: Int, b: Int): Int {
    // Return the sum
    return a + b
}

fun main() {
    val result = add(3, 4) // Call add function
    println("The sum is: $result")
}
OutputSuccess
Important Notes

Use comments to make your code easier to understand, but avoid obvious comments that just repeat the code.

Documentation comments start with /** and are used by tools to create API docs.

Keep comments up to date when you change your code to avoid confusion.

Summary

Comments explain your code and help others understand it.

Use // for single-line and /* ... */ for multi-line comments.

Documentation comments /** ... */ describe code elements and help generate docs.