Kotlin Comments
Introduction
Comments are non-executable text included in code to provide explanations, document code behavior, or temporarily disable code sections. In Kotlin, comments serve as notes to yourself or other developers about how your code works, why certain decisions were made, or what needs to be improved.
Using comments effectively is a fundamental programming practice that makes your code more readable, maintainable, and collaborative. In this tutorial, we'll explore the different types of comments in Kotlin and best practices for using them.
Types of Comments in Kotlin
Kotlin supports three types of comments: single-line comments, multi-line comments, and documentation comments (KDoc).
Single-Line Comments
Single-line comments start with two forward slashes (//
) and continue until the end of the line.
// This is a single-line comment
val name = "Kotlin" // This comment is at the end of a code line
Single-line comments are perfect for brief explanations or notes about a specific line of code.
Multi-Line Comments
Multi-line comments start with /*
and end with */
. Everything between these delimiters is treated as a comment, even if it spans multiple lines.
/* This is a multi-line comment.
You can write as many lines as you want.
The compiler will ignore all of this text. */
val language = "Kotlin"
Multi-line comments are useful for longer explanations or when you need to temporarily disable multiple lines of code.
Documentation Comments (KDoc)
KDoc comments are special comments used to generate documentation for your code. They start with /**
and end with */
:
/**
* This function calculates the sum of two integers.
*
* @param a First integer
* @param b Second integer
* @return The sum of a and b
*/
fun sum(a: Int, b: Int): Int {
return a + b
}
KDoc comments support Markdown syntax and special tags that start with @
, like @param
and @return
, which provide structured information about parameters, return values, and more.
Practical Examples
Example 1: Using Comments for Code Documentation
/**
* User class represents a user in the system.
*
* @property id Unique identifier for the user
* @property name User's full name
* @property email User's email address
*/
class User(
val id: Int, // Unique identifier
val name: String, // Full name
val email: String // Email address
)
// Create a new user
val newUser = User(
id = 1001,
name = "John Doe",
email = "[email protected]"
)
Example 2: Using Comments to Explain Complex Logic
fun calculateDiscount(price: Double, customerType: String): Double {
// Base discount rate
var discount = 0.0
/* Apply different discount rates based on customer type:
- Regular: 5%
- Premium: 10%
- VIP: 15%
- Employee: 20% */
when (customerType.lowercase()) {
"regular" -> discount = 0.05
"premium" -> discount = 0.10
"vip" -> discount = 0.15
"employee" -> discount = 0.20
else -> discount = 0.0 // No discount for unrecognized customer types
}
// Calculate final price after discount
return price * discount
}
Example 3: Using Comments to Disable Code (Commenting Out)
fun processOrder(order: Order) {
// Validate order
validateOrder(order)
// Update inventory
updateInventory(order)
// Process payment
processPayment(order)
/* Temporarily disabling email notification for testing
if (order.status == "COMPLETED") {
sendEmailConfirmation(order.customerEmail)
}
*/
// Log order completion
logOrderCompletion(order)
}
Best Practices for Using Comments
-
Write Clear and Concise Comments Comments should be clear, concise, and provide value. Avoid stating the obvious.
kotlin// Bad comment - obvious
val total = price + tax // Adds tax to price
// Good comment - explains why
val total = price + tax // Including tax for final display to customer -
Keep Comments Updated When you change code, update related comments to prevent misleading information.
-
Use Comments to Explain "Why", Not "What" Your code should already express what it's doing. Comments should explain why it's doing it.
kotlin// Bad approach
// Set the count to 1
count = 1
// Better approach
// Reset counter when starting a new session
count = 1 -
Use TODO Comments for Pending Tasks Kotlin and most IDEs recognize special comment markers like
TODO
andFIXME
.kotlin// TODO: Implement validation for email format
// FIXME: This function has performance issues with large data sets -
Avoid Over-Commenting Too many comments can make code harder to read. Focus on the parts that need explanation.
Summary
Comments in Kotlin are powerful tools for documenting code, explaining complex logic, and improving code maintainability. By using single-line comments for brief notes, multi-line comments for longer explanations, and KDoc for formal documentation, you can create code that is easier for you and others to understand.
Remember that the best code is self-explanatory, with comments supplementing rather than replacing clear code. A good balance of well-written code and strategic commenting will make your Kotlin projects more professional and collaborative.
Exercises
- Write a function with appropriate KDoc comments that calculates the area of a rectangle.
- Comment an existing piece of code using single-line comments to explain its purpose.
- Use multi-line comments to document a complex algorithm or business rule.
- Review some code you've written and add
TODO
comments for improvements you could make. - Try to refactor a piece of code to make it clearer, reducing the need for explanatory comments.
Additional Resources
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)