Kotlin Comments
Comments let you leave notes in your code that the Kotlin compiler ignores completely, making programs easier for humans to understand later.
Why Use Comments?
As programs grow, it becomes harder to remember why a particular piece of code exists. Comments let you record that reasoning directly next to the code itself. The Kotlin compiler skips over comments entirely, so they have zero effect on how your program runs - they exist purely for the humans reading the code.
Single-Line Comments
A single-line comment starts with two forward slashes, //. Everything from // to the end of that line is ignored by the compiler, whether it appears on its own line or after a piece of code.
Using // Comments
fun main() {
// This prints a welcome message
println("Welcome!") // runs once at startup
}Multi-Line Comments
A multi-line, or block, comment starts with /* and ends with */, and everything in between is ignored, even if it spans several lines. Block comments are handy for longer explanations or for temporarily disabling a chunk of code.
Using /* */ Comments
/*
* This program greets the user.
* It is a simple example of a block comment.
*/
fun main() {
println("Hello there!")
}- Explain why the code does something, not just what it does
- Keep comments up to date - an outdated comment is worse than no comment
- Avoid stating the obvious, like // declare a variable above val x = 5
- Use documentation comments for anything other code will rely on as an API
A Documentation Comment
/**
* Calculates the total price for an order.
* @param quantity number of items purchased
* @param unitPrice price of a single item
* @return the total cost
*/
fun calculateTotal(quantity: Int, unitPrice: Double): Double {
return quantity * unitPrice
}
fun main() {
println(calculateTotal(3, 2.5))
}Exercise: Kotlin Comments
Which symbol starts a single-line comment in Kotlin?