Comments in Kotlin
In this page:
Single-Line Comments
A double slash // marks everything after it on that line as a comment, which the compiler ignores entirely. This is the most common way to leave short notes next to code.
Example: Single-Line Comments
fun main() {
// This line prints a greeting
println("Hello!") // greeting printed here
}
Login to try C/C++/Java/PHP code in the editor
Multi-Line Block Comments
Wrapping text in /* and */ creates a block comment that can span multiple lines, useful for longer explanations. Kotlin, unlike Java, even allows these block comments to be nested inside each other.
Example: Multi-Line Block Comments
fun main() {
/*
* This program demonstrates block comments.
* They can span several lines.
*/
println("Block comments explained above")
}
Login to try C/C++/Java/PHP code in the editor
Documentation Comments (KDoc)
Comments starting with /** are KDoc comments, used to document functions and classes so tools can generate reference documentation automatically, similar to Javadoc in Java.
Example: Documentation Comments (KDoc)
/**
* Greets a person by name.
*/
fun greet(name: String) {
println("Hello, $name!")
}
fun main() {
greet("Kotlin")
}
Login to try C/C++/Java/PHP code in the editor
Writing Useful Comments
The best comments explain *why* a piece of code exists or a decision was made, not what it obviously does. Comments that only restate the code add clutter without adding understanding.
Note: If you feel the need to comment *what* a line does, consider renaming variables/functions to make the code self-explanatory instead.
Example: Writing Useful Comments
fun main() {
// Using 0.5 as a discount rate agreed with the finance team
val discountRate = 0.5
println("Discount rate: $discountRate")
}
Login to try C/C++/Java/PHP code in the editor
- Forgetting that
//only comments out the rest of that single line, so code after it on the same line is fine but the next line still runs normally. - Nesting
/* */block comments incorrectly, not realizing Kotlin actually does support nested block comments unlike Java. - Writing comments that just repeat what the code already says, instead of explaining *why* it exists.
//starts a single-line comment that continues to the end of that line./* ... */marks a multi-line block comment, and Kotlin allows these to be nested.- KDoc comments start with
/** ... */and are used to generate documentation for functions and classes. - Good comments explain intent and reasoning, not just restate what the code obviously does.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: