kotlinkotlin-dokka

How is `@sample` used in ktdoc?


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.


Solution

  • 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")
      }
    }