МагазинНовостиПравилаПомощьДокументацияПрисоединиться

Comments

Here comes a comet. Oh, sorry, comments. What are they? Well, it is a special text that will be ignored by the compiler. Comments allow you to clarify a piece of code or exclude it from the compilation process (that is, disable it). Throughout this course, we will use comments to explain how and why our code works.

There are three kinds of comments in Kotlin.

End-of-line comments

The compiler ignores any text from // to the end of the line.

fun main() {
    // The line below will be ignored
    // println("Hello, World")

    // This prints the string "Hello, Kotlin"
    println("Hello, Kotlin")  // Here can be any comment
}

Have you known? In most code editors, a line can be commented by placing the caret on the line and pressing Ctrl /.

Multi-line comments

The compiler ignores any text from /* to the corresponding */. You can use it for writing single-line as well as multiple-line comments:

fun main() {
    /* This is a single-line comment */
    /*  This is an example of
        a multi-line comment */

    /* All lines below will be ignored
        println("Hello")
        println("World")
    */
}

You can put comments inside other comments. When writing nested multi-line comments, make sure opening / and closing / make pairs.

fun main() {
    /*
    println("Hello")  // print "Hello"
    println("Kotlin") /* print "Kotlin" */
    */
}

Documentation comments (doc comments)

The compiler ignores any text from /** to the corresponding */ just like it ignores text in multi-line comments.

You can use this kind of comments to automatically generate documentation about your source code using a special tool. Usually, these comments are placed above the declarations of some program elements. Also, in this case, some special labels such as @param, @return and others are used for controlling the tool.

Let's take a look at the example below.

/**
 * The `main` function accepts string arguments from outside.
 *
 * @param args arguments from the command line.
 */
fun main(args: Array<String>) {
    // do nothing
}

Do not be afraid if you don’t completely understand documentation comments yet. Later we take a closer look at them.

Remember, lots of comments in a program do not make it absolutely clear. The code may change, and the comments will become outdated. To reduce the number of comments, you should write self-documenting code, which might not be that simple for padawans. We will learn to do it during the course.