问题描述
我想在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")
}
}