Code Comments in Kotlin

It is imperative to for us understand code comments before we delve further to understand basics of Kotlin. Developers who have worked on large projects do understand the need of code comments. Understand from the perspective of a developer, who have recently been asked to fix a project. If the project contained few lines of code then it could be fixed in seconds. But, what if our code comprises of thousands of lines then it may take hours or days to fix it. All the time lost could have been put to some good use if our code was commented properly. Under such scenario, all the developer had to do was just read code comments and move to the section where alteration was required.

Kotlin just like other programming languages allow us to write code comments. There are two ways to comment our code –

  1. Single-line Comments,
  2. Multi-line or Block comments.

In addition to, the comments which we write along-side or in-between our code are ignored by the compiler.

1. Single-line Comments: These are preceded by // and can also be provided as end-of-line comments. For instance –

// This is single-line comment
val a=4 // This is an end-of-line comment

For single-line or end-of-line comments, anything written after // is ignored by the compiler. In case our comment are spread over multiple lines then we can provide // in the beginning of every line. For instance –

// This a single-line
// comment
// spread over multiple lines.

But, this not considered a good practice. For such a scenario, it is best to go with multi-line comments.

2. Multi-line or Block Comments: Block comments are spread over multiple lines. Such comments start with /* and end with */. Anything written in-between is ignored by the compiler. For instance –

/* This is a multi-line comment
or Block comment
spread over multiple lines. */

It is worth mentioning here that Kotlin allows nested comments. Nested comments are comments inside other comments. For instance –

/* This is a multi-line comment
or Block comment
               /* Nested Comments
                   explained
               */
spread over multiple lines. */

Note: Only Block or Multi-line comments can be nested in Kotlin.

In conclusion, in this article we have discussed single-line and block comments and their significance.