ktdoc中如何使用@sample?

问题描述

我想在Kotlin文档中提供代码示例,我发现the documentation中有一个@sample <identifier>关键字。但是我不确定该怎么做。

解决方法

您在ktdoc块中使用@sample <identifier>

<identifier>是示例函数的全名。

示例函数包含您要显示的所有代码。这样,编译器将验证代码。

/**
 * Creates an [Iterator] for an [java.util.Enumeration],allowing to use it in `for` loops.
 * @sample samples.collections.Iterators.iteratorForEnumeration
 */
@kotlin.jvm.JvmVersion
public operator fun <T> java.util.Enumeration<T>.iterator(): Iterator<T> = object : Iterator<T> {
    override fun hasNext(): Boolean = hasMoreElements()

    public override fun next(): T = nextElement()
}

@Sample
fun iteratorForEnumeration() {
  val vector = Vector<String>().apply {
    add("RED")
    add("GREEN")
    add("BLUE")
  }
  for (e in vector.elements()) {
    println("The element is $e")
  }
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...