如何在Kotlin数据类中记录属性?

Hon*_*dek 7 java javadoc kotlin kdoc

我应该在哪里将Javadoc用于Kotlin数据类中的属性?

换句话说,如何在Kotlin中编写以下Java代码:

/**
 * Represents a person.
 */
public class Person {
    /**
     * First name. -- where to place this documentation in Kotlin?
     */
    private final String firstName;
    /**
     * Last name. -- where to place this documentation in Kotlin?
     */
    private final String lastName;

    // a lot of boilerplate Java code - getters, equals, hashCode, ...
}
Run Code Online (Sandbox Code Playgroud)

在Kotlin看起来像这样:

/**
 * Represents a person.
 */
data class Person(val firstName: String, val lastName: String)
Run Code Online (Sandbox Code Playgroud)

但是在哪里放置属性的文档?

yol*_*ole 13

文档中所述,您可以使用@property标记:

/**
 * Represents a person.
 * @property firstName The first name.
 * @property lastName The last name.
 */
data class Person(val firstName: String, val lastName: String)
Run Code Online (Sandbox Code Playgroud)

或者,如果您在文档中没有太多关于它们的说法,只需在类的描述中提及属性名称:

/**
 * Represents a person, with the given [firstName] and [lastName].
 */
data class Person(val firstName: String, val lastName: String)
Run Code Online (Sandbox Code Playgroud)

  • 这是故意的。有关原因的说明,请参见http://kotlinlang.org/docs/reference/coding-conventions.html#documentation-comments。 (3认同)
  • 遗憾的是,当我在类前面输入`/ **`时,IntelliJ Idea不会生成骨架-类似于方法参数的*方式。这是对我们进行教育的机会:) (2认同)