androidengineers.Book a session

Kotlin Basics and Syntax

Comments and KDoc Basics

article15 minEasy

Document the contract and the reason

Use comments to explain constraints or decisions that are not obvious from code. KDoc begins with /** and describes declarations for readers and generated documentation. A useful function contract explains accepted inputs, the result, and meaningful failures.

/**
 * Divides a study budget into complete blocks.
 * @param minutes non-negative available minutes
 * @param blockMinutes positive size of one block
 * @throws IllegalArgumentException if either argument is invalid
 */
fun blockCount(minutes: Int, blockMinutes: Int): Int {
    require(minutes >= 0)
    require(blockMinutes > 0)
    return minutes / blockMinutes
}

Documenting “divides minutes by blockMinutes” adds little. Explaining that partial blocks are excluded tells callers something important. Keep examples aligned with actual behavior; inaccurate comments are harder to detect than compiler errors.

Use links such as [blockCount] when referring to Kotlin declarations. Avoid placing personal information or tokens in examples, since generated docs can become public.

Exercise

Add KDoc to a function that normalizes a username. Decide whether it trims spaces, changes case, and rejects blank input. Include an example and tests for every promise you document.

Check: another developer should be able to call the function correctly without reading its implementation.

Reference: KDoc

YOUR LEARNING JOURNEY

0 of 110 available lessons completed

Progress saved in this browser. No account needed.
Comments and KDoc Basics | Kotlin Core Programming | Android Engineers