LAST UPDATED: JULY 18, 2020
Kotlin Comments
In this tutorial, we will cover comments in Kotlin. Comments are an essential part of the code. Sometimes it is difficult for programmers to understand a piece of code written by other programmers. To make our code more readable and understandable, we should add comments and document it properly.
Comments are completely ignored by the compilers. Hence, they will not cause any error while compiling the code.
There are two types of comments in Kotlin:
-
Single line comment
-
Multi-line comment
Now we will see how to use them in Kotlin.
Single Line Comment in Kotlin
As the name suggests, single-line comments are used to write comments in a single line. They are created using //
(double slash). Single line comments should span across a single line only and not to multiple lines, else we will get an error.
Here is an example:
// This is a comment
println("Enter string: ") // Enter a string here
var inputString = readLine()
println("Input in string format is: $inputString") // Input is printed here
In the code above, there are three comments (in line numbers 1, 2, and 4).
Multi-Line Comments Kotlin
Multi-line comments span across multiple lines. It starts with /*
and ends with */
.
/*
This is a multi-line comment
This is second line
Last line of comment
*/
println("Enter string: ")
var inputString = readLine()
println("Input in string format is: $inputString")
Multiline comments can be used to explain what a function does along with explaining its parameters. Or we can multiline comments where we have to document so crucial algorithm steps in our program, or anywhere where detailed comments are required.
Summary
In this tutorial we discussed about comments in Kotlin. Comments are useful tool and we should use it wisely to make our code more readable and to document what the code does within the program.