4

I want to offer code samples in my Kotlin documentation and I found there's a @sample <identifier> keyword in the documentation. But I'm not sure what I'm supposed to do.

helios
  • 13,574
  • 2
  • 45
  • 55

1 Answers1

5

You use @sample <identifier> in the ktdoc block.

<identifier> is the full name of the sample function.

The sample function contains all the code you want to show. That way the compiler verifies the code.

/**
 * 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")
  }
}
helios
  • 13,574
  • 2
  • 45
  • 55
  • 1
    i got **unresolved reference** with `@Sample` – Mahmoud Mabrok Mar 02 '22 at 14:38
  • the "unresolved reference" is because the Kotlin samples jar is not supplied along with the Kotlin stdlib by default and should be downloaded separately: https://stackoverflow.com/questions/67558167/is-there-a-way-to-open-kotlin-samples-in-intellij – Stefan Nov 02 '22 at 17:27