Including sample code in kdocs that is tested

We've got the kdoc documentation for the standard library (which is like javadoc but based on kotlin and allows markdown wiki syntax). When looking at documentation for functions, its often very useful to see some example code of how to use an API. Also including code directly inside comments soon gets stale and isn't refactoring safe.

So kdoc now lets you include test function blocks to demonstate how a function works and how it should be used. This lets the documentation include code which is automatically tested and helps folks validate both the documentation and the tests; the more eyes on both the better. It also provides a more natural way for people to navigate from the documentation to test code to help learn more about the APIs.

For example the kotlin package defines a bunch of helper functions and extension functions. In particularly the extensions on java.util.Collection provide lots of handy helper methods. If you look at a few functions for example


You’ll see some example test code that demonstrates how to use the function. There is documentation on writing comments in kotlin, in particular to link to a block of test code just include the @includeFunction macro with the relative source file and name of the function to include. For example

Awesome!

Seems like @includeFunction is including the function body and not the whole function.  Perhaps it should get renamed to @includeFunctionBody.
Including the whole function might be handy in some cases.  It might also be handy to support the same for classes/objects to be able to document more complete examples.

Regards,
Hiram

1 Like

Very nice.

We now have syntax highlighting too BTW. e.g. all(). You might have to hit reload in your browser

Great catch Hiram :)

I’ve renamed the macro to @includeFunctionBody as you suggest, its clearer…

https://github.com/JetBrains/kotlin/blob/master/libraries/stdlib/src/kotlin/Iterators.kt#L6

It has been renamed to @sample in the mean time.

1 Like