Comments
Kotlin has line comments with //, block comments with /* */ that can nest, and KDoc comments with /** */ that document declarations; good comments explain why, not what.
Write comments that explain intent while leaving behavior in executable code.
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.