kotlincompilationcommentscode-documentation

Rust-like comment compilation for kotlin/java?


in short, rust compiler can compile certain code in comments, such as example code, against the actual code - resulting in always up to date commentary.

Anyone aware of any sort-of-equivalent for Kotlin or Java Code? Any suggestions?

Had a hard time googling for it.

What i long for is basically:

/**
 * some descriptive text
 * 
 * Example:
 * ```
 * val foo = bar();
 * assert(foo == "bar"); 
 * ```
 *
 * @return "bar" as String
**/
fun bar() = "bar";

the example, just like an automated test, should fail when bar changes its return value. otherwise become a part of the documentation as sample code.


Solution

  • One approach I just discovered would be to use the KDoc @sample tag to build associated sample code which would then be embedded in the Dokka-generated documentation.

    I found this article which elaborates on that approach and also points out some drawbacks like sub-optimal rendering. But it's certainly a good start in that direction.