Kotlin Comments
Comments are notes for humans. The compiler ignores them completely, so they never change what your program does. Use them to explain why code exists, to leave reminders, or to temporarily switch off a line while experimenting.
Single-line comments
Two slashes // start a comment that runs to the end of the line. It can stand on its own line or follow code:
fun main() {
// Greet the user
println("Good morning!")
println("Have a nice day") // printed second
}Good morning!
Have a nice day
Multi-line comments
Text between /* and */ is a comment, however many lines it spans:
fun main() {
/*
This program prints the opening hours.
They were last updated in spring.
*/
println("Mon-Fri: 8:00-18:00")
println(/* inline comment */ "Sat: 9:00-13:00")
}Mon-Fri: 8:00-18:00
Sat: 9:00-13:00
Unlike Java and C, Kotlin's block comments can be nested — handy when you comment out a block that already contains a comment:
fun main() {
/*
println("old code")
/* an older note */
println("more old code")
*/
println("Only this line runs")
}Only this line runs
Commenting out code
A quick way to see what a line does is to disable it. In IntelliJ and Android Studio, Ctrl+/ toggles // on the selected lines.
fun main() {
println("Step 1")
// println("Step 2 - disabled while testing")
println("Step 3")
}Step 1
Step 3
Documentation comments (KDoc)
Comments starting with /** are KDoc comments. IDEs show them as tooltips and the Dokka tool turns them into HTML documentation. Tags like @param and @return describe parts of a function:
/**
* Calculates the price after a discount.
*
* @param price the original price in euros
* @param percent the discount, from 0 to 100
* @return the reduced price
*/
fun discounted(price: Double, percent: Int): Double =
price * (100 - percent) / 100KDoc also supports Markdown and links to other code with square brackets, e.g. [discounted].
Comment types at a glance
| Syntax | Kind | Typical use |
|---|---|---|
// text |
single-line | short notes, disabling a line |
/* text */ |
block (nestable) | longer explanations, disabling blocks |
/** text */ |
KDoc | documenting public functions and classes |
Tip: Good comments explain why, not what.
count++ // increase countadds nothing;count++ // the header row is not a productis genuinely useful.
Test yourself
Which syntax starts a single-line comment in Kotlin?
- #
- --
- //
- <!--
What is special about Kotlin block comments compared with Java?
- They can be nested
- They must be on one line
- They are printed at runtime
- They use # instead of /*
Which comment style is used for API documentation (KDoc)?
- // doc
- /* doc */
- /** doc */
- ### doc