Instruction 5
Using Comments
Comments are a way to leave notes in your code and aren’t interpreted as part of the code. These notes could be short or long. For short comments, write your notes after // followed by a space. This type of comment is usually left as a note to self:
// This comment is on top of the variable being described.
const val WEEKLY_INTEREST = 100 // This comment is beside the variable being described.
This is known as a single-line or end-of-line comment.
Note: Putting the comments above or beside the code is a personal preference. Do whatever is consistent with an existing program, or stick to one style if it’s a new one. Keep it short and descriptive.
Or you could make your comment span multiple lines by writing the text between /* and */. This is known as a block comment:
/* This is known
as a block comment. */
const val WEEKLY_INTEREST = 100
For even longer comments, put your text in between /** and */. This is known as documentation comments. They’re used by documentation tools to create documents from the comment text. Try the following:
/** This comment is a longer comment giving further information about the variable. */
const val WEEKLYINTEREST = 100
If it spans several lines, which is the ideal case, new lines should start with a * followed by a space:
/**
* This comment is longer
* giving further information about the
* variable.
*/
const val WEEKLY_INTEREST = 100
Documentation comments are designed for adding extra detail and explanations about a piece of code. You can add documentation comments to anything: classes, variables or functions.
Note: Documentation comments in Kotlin use the KDoc language. KDoc provides several features. These features enable you to write rich comments with proper formatting.
Kotlin comment blocks can begin with a single slash and asterisk, /*, and do not need to have astericks at the beginning of each line. Documentation tools will not create documentation from comment blocks beginning with /*:
/*
This comment is longer.
It has more information.
This is a valid comment block, but cannot be used with automatic document creation tools.
*/
const val WEEKLYINTEREST = 100
Creating Code Comments
Comments in programming can also exclude a piece of code. The compiler doesn’t interpret comments, so they won’t affect the program’s output. Consider the following example:
// const val WEEKLY_INTEREST = 100 /** This code is said to be commented out.*/
const val WEEKLY_INTEREST = 200
Since the first declaration for WEEKLY_INTEREST is commented out, you can redeclare it in the same scope without any issue. To undo the comment is to remove the comment symbols.