Comments
Six months from now, someone opens the café code and finds if (cups >= 10) price = 0.0. Is that a bug or a promotion? One well-placed sentence would have told them. Comments are notes the compiler ignores and people rely on.
The rule
Code says what; comments say why.
Kotlin has three kinds of comment:
// A line comment runs to the end of the line.
/* A block comment
can span several lines. */
/**
* A KDoc comment documents the declaration below it.
* @param cups drinks bought so far, including this one
* @return 0.0 for a free drink, otherwise the menu price
*/
fun loyaltyPrice(cups: Int, price: Double): Double =
if (cups % 10 == 0) 0.0 else price // every tenth drink is free//is for short notes, including at the end of a line of code./* … */covers several lines. Unlike Java, Kotlin block comments nest: a/* … */inside another one is fine, which makes it safe to comment out code that already contains a block comment./** … */is KDoc, Kotlin's documentation format. It sits directly above a class, function or property. Tags such as@param,@returnand@throwsdescribe the parts, and it supports Markdown like**bold**and[references]to other names. IDEs show KDoc when you hover, and tools such as Dokka turn it into a documentation website.
What makes a comment good? It survives changes to the code. // add 1 to cups goes stale the moment someone edits the line. // counts the free drink too, so the tenth cup triggers the offer stays true and explains a decision you could not guess from the code.
The shortcut
Before writing a comment, cover the code and read only the comment. If it tells you nothing the code would not, delete it or rewrite it as a reason. If the code is confusing, first try a better name; comment only what a name cannot say.
The original
val t = p * 1.05 // multiply p by 1.05
A common trap is leaving large blocks of old code commented out "just in case". Version control remembers old code; comments should not.
Drills
Answer fast — trust the rule.
Which comment adds the most value?
Which opener starts a KDoc documentation comment?
What happens with /* outer /* inner */ still outer */ in Kotlin?
In KDoc, which tag describes a function's parameter?
Remember
- Code says what; comments say why.
//for a line,/* */for a block (and it nests),/** */for KDoc.- Cover the code: if the comment says nothing new, delete or rewrite it.
