如何在Kotlin数据类中记录属性?KDoc属性文档位置在哪?
How to Document Properties in Kotlin Data Classes & Map Java Javadocs to KDoc
Great question—Kotlin's KDoc has a straightforward pattern for mapping Java-style property documentation, even in data classes. Let's break down both of your questions with clear examples.
1. Adding Documentation to Kotlin Data Class Properties
Kotlin data classes lean into primary constructor parameters (marked with val or var) to define properties. There are two scenarios for adding docs:
- Primary constructor properties: Add KDoc directly above the constructor parameter (since
val/varturns it into a class property automatically). - Class-body properties: If you define a property inside the class body (not in the primary constructor), add KDoc above the property definition itself.
2. Mapping Java Property Javadocs to Kotlin KDoc
In your Java example, the Javadocs for firstName and lastName are tied to the field declarations. For Kotlin data classes, these translate directly to primary constructor parameters—so you’ll move those Javadoc comments to sit above the corresponding parameters in the data class’s primary constructor.
Here’s the direct Kotlin equivalent of your Java code, with proper KDoc:
/** * Represents a person. */ data class Person( /** * First name of the person. (Matches your Java Javadoc for firstName) */ val firstName: String, /** * Last name of the person. (Matches your Java Javadoc for lastName) */ val lastName: String )
Bonus: Documenting Class-Body Properties
If you ever need to add a property inside the data class body (not part of the primary constructor), document it just like a regular Kotlin property:
/** * Represents a person. */ data class Person( val firstName: String, val lastName: String ) { /** * Full name formed by combining the first and last name. */ val fullName: String get() = "$firstName $lastName" }
When generating docs with Dokka (Kotlin’s official documentation tool), these KDoc comments will appear alongside the properties exactly like your original Java Javadocs did for fields.
内容的提问来源于stack exchange,提问作者Honza Zidek

