Kotlin comments are non-executable text annotations that developers add to their source code to explain functionality, document methods, or provide context about specific code sections. The Kotlin compiler completely ignores these comments during compilation, making them perfect for code documentation without impacting performance.
Kotlin supports three primary types of comments that serve different purposes in code documentation and explanation.
Single-line Kotlin comments begin with two forward slashes (//
) and extend to the end of the current line. These comments are perfect for brief explanations or quick notes about specific code lines.
// This is a single-line Kotlin comment
val userName = "KotlinDeveloper" // Inline comment explaining the variable
Immediate Termination: Single-line Kotlin comments automatically end at the line break, making them ideal for short explanations.
val age = 25 // User's current age
val city = "New York" // User's location
Inline Usage: You can place single-line Kotlin comments at the end of code lines to provide context without creating separate documentation lines.
val pi = 3.14159 // Mathematical constant for circle calculations
Code Deactivation: Single-line Kotlin comments are excellent for temporarily disabling code during debugging or testing phases.
println("Active code")
// println("Temporarily disabled code")
Multi-line Kotlin comments start with /*
and end with */
, allowing developers to write extensive explanations spanning multiple lines. These comments are particularly useful for detailed function descriptions or complex algorithm explanations.
/*
This is a multi-line Kotlin comment
that can span across several lines
and provide detailed explanations
*/
Flexible Length: Multi-line Kotlin comments can extend across numerous lines, making them perfect for comprehensive documentation.
/*
This function calculates the compound interest
based on principal amount, interest rate, and time period.
It uses the standard compound interest formula:
A = P(1 + r
)^(nt)
*/
fun calculateCompoundInterest(principal: Double, rate: Double, time: Int): Double {
return principal * Math.pow(1 + rate/100, time.toDouble())
}
Nested Structure Support: Multi-line Kotlin comments can contain other comment-like text without interfering with the comment block.
/*
Example usage:
// val result = calculateArea(5.0, 3.0)
This demonstrates how to call the function
*/
Block Documentation: Multi-line Kotlin comments are ideal for documenting entire code blocks or explaining complex business logic.
/*
User authentication flow:
1. Validate input credentials
2. Check against database
3. Generate authentication token
4. Return success/failure status
*/
KDoc comments are specialized Kotlin comments used for generating API documentation. These comments follow a specific format and support various tags for structured documentation.
/**
* This is a KDoc comment for documentation generation
* @param parameter description of the parameter
* @return description of the return value
*/
Documentation Generation: KDoc comments integrate with documentation tools to automatically generate API references and help files.
/**
* Calculates the area of a rectangle
* @param length the length of the rectangle
* @param width the width of the rectangle
* @return the calculated area as Double
*/
fun calculateRectangleArea(length: Double, width: Double): Double {
return length * width
}
Structured Tags: KDoc comments support various tags like @param
, @return
, @throws
, and @see
for comprehensive documentation.
/**
* Divides two numbers safely
* @param dividend the number to be divided
* @param divisor the number to divide by
* @return the division result
* @throws ArithmeticException when divisor is zero
*/
fun safeDivide(dividend: Double, divisor: Double): Double {
if (divisor == 0.0) throw ArithmeticException("Cannot divide by zero")
return dividend / divisor
}
Cross-Reference Support: KDoc comments can reference other classes, methods, or properties using special linking syntax.
/**
* User data class for authentication
* @see UserRepository for database operations
* @see AuthenticationService for login functionality
*/
data class User(val username: String, val email: String)
Kotlin supports nested comments, where you can place one comment type inside another. This feature is particularly useful during development and debugging phases.
Multi-line Within Single-line: You cannot nest multi-line comments within single-line comments due to syntax limitations.
// This is valid: /* nested comment */ within single-line
Comment Block Nesting: Multi-line Kotlin comments can contain single-line comment syntax without breaking the comment block.
/*
This is a multi-line comment
// This single-line syntax is treated as regular text
Still within the multi-line comment
*/
Debugging Advantage: Nested Kotlin comments help developers comment out large code blocks that already contain comments.
/*
Temporarily disabled function:
fun processData() {
// Process user input
val result = calculateValue()
/* Complex calculation logic */
return result
}
*/
Understanding where to place Kotlin comments effectively enhances code readability and maintenance.
/**
* Represents a bank account with basic operations
* Supports deposit, withdrawal, and balance inquiry
*/
class BankAccount(private var balance: Double) {
// Class implementation
}
/**
* Validates email address format
* @param email the email string to validate
* @return true if email is valid, false otherwise
*/
fun isValidEmail(email: String): Boolean {
// Email validation logic using regex
val emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+"
return email.matches(emailPattern.toRegex())
}
// Database connection timeout in milliseconds
private val connectionTimeout = 5000
/*
Configuration settings for the application
These values are loaded from external properties file
*/
private val appConfig = loadConfiguration()
Here’s a comprehensive example demonstrating all types of Kotlin comments in a practical scenario:
/**
* Shopping Cart Management System
* Handles product additions, removals, and total calculations
* @author KotlinDeveloper
* @version 1.0
* @see Product for item details
*/
class ShoppingCart {
// List to store cart items
private val items = mutableListOf<CartItem>()
/*
Tax rate applied to all purchases
This value might change based on location
Currently set to 8.5% for demonstration
*/
private val taxRate = 0.085
/**
* Adds a product to the shopping cart
* @param product the product to add
* @param quantity number of items to add
* @throws IllegalArgumentException if quantity is negative
*/
fun addItem(product: Product, quantity: Int) {
// Validate input parameters
if (quantity < 0) {
throw IllegalArgumentException("Quantity cannot be negative")
}
/*
Check if product already exists in cart
If exists, update quantity; otherwise, add new item
*/
val existingItem = items.find { it.product.id == product.id }
if (existingItem != null) {
existingItem.quantity += quantity // Update existing item
} else {
items.add(CartItem(product, quantity)) // Add new item
}
}
/**
* Removes a product from the shopping cart
* @param productId the ID of the product to remove
* @return true if item was removed, false if not found
*/
fun removeItem(productId: String): Boolean {
// Find and remove item with matching product ID
return items.removeIf { it.product.id == productId }
}
/**
* Calculates the total cart value including tax
* @return the total amount with tax applied
*/
fun calculateTotal(): Double {
// Calculate subtotal from all items
val subtotal = items.sumOf { it.product.price * it.quantity }
/*
Apply tax calculation:
Total = Subtotal + (Subtotal * Tax Rate)
*/
val tax = subtotal * taxRate
return subtotal + tax // Return final total
}
/**
* Displays cart contents with formatted output
*/
fun displayCart() {
println("=== Shopping Cart Contents ===")
// Check if cart is empty
if (items.isEmpty()) {
println("Your cart is empty")
return
}
/*
Display each item with details:
- Product name and price
- Quantity and subtotal
*/
items.forEach { item ->
val itemTotal = item.product.price * item.quantity
println("${item.product.name} - $${item.product.price} x ${item.quantity} = $${itemTotal}")
}
// Display final totals
val subtotal = items.sumOf { it.product.price * it.quantity }
val tax = subtotal * taxRate
val total = subtotal + tax
println("------------------------")
println("Subtotal: $${String.format("%.2f", subtotal)}")
println("Tax (${(taxRate * 100)}%): $${String.format("%.2f", tax)}")
println("Total: $${String.format("%.2f", total)}")
}
}
/**
* Represents a product in the store
* @property id unique identifier for the product
* @property name display name of the product
* @property price cost per unit
*/
data class Product(
val id: String,
val name: String,
val price: Double
)
/**
* Represents an item in the shopping cart
* @property product the product information
* @property quantity number of items
*/
data class CartItem(
val product: Product,
var quantity: Int
)
// Main function to demonstrate the shopping cart system
fun main() {
/*
Create sample products for testing
These represent items that might be in an online store
*/
val laptop = Product("LAPTOP001", "Gaming Laptop", 1299.99)
val mouse = Product("MOUSE001", "Wireless Mouse", 29.99)
val keyboard = Product("KEYBOARD001", "Mechanical Keyboard", 149.99)
// Initialize shopping cart
val cart = ShoppingCart()
// Add items to cart with different quantities
cart.addItem(laptop, 1) // Add one laptop
cart.addItem(mouse, 2) // Add two mice
cart.addItem(keyboard, 1) // Add one keyboard
/*
Display cart contents and total
This will show all items with calculated tax
*/
cart.displayCart()
// Demonstrate item removal
println("\n--- Removing mouse from cart ---")
cart.removeItem("MOUSE001")
cart.displayCart()
}
Expected Output:
=== Shopping Cart Contents ===
Gaming Laptop - $1299.99 x 1 = $1299.99
Wireless Mouse - $29.99 x 2 = $59.98
Mechanical Keyboard - $149.99 x 1 = $149.99
------------------------
Subtotal: $1509.96
Tax (8.5%): $128.35
Total: $1638.31
--- Removing mouse from cart ---
=== Shopping Cart Contents ===
Gaming Laptop - $1299.99 x 1 = $1299.99
Mechanical Keyboard - $149.99 x 1 = $149.99
------------------------
Subtotal: $1449.98
Tax (8.5%): $123.25
Total: $1573.23
This comprehensive example demonstrates how Kotlin comments enhance code understanding, provide documentation for future maintenance, and help other developers quickly grasp the functionality of complex systems. The combination of single-line comments, multi-line comments, and KDoc comments creates a well-documented codebase that’s both professional and maintainable.