2

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.

MomStopFlashing
  • 255
  • 1
  • 2
  • 7
  • Is what you're describing different than what's explained here? https://doc.rust-lang.org/book/ch14-02-publishing-to-crates-io.html – Tenfour04 Jun 20 '23 at 14:07
  • actually its the very same - except that i need this for kotlin ;) – MomStopFlashing Jun 20 '23 at 14:33
  • It's called [KDoc](https://kotlinlang.org/docs/kotlin-doc.html) in Kotlin and Javadoc in Java. – Tenfour04 Jun 20 '23 at 14:56
  • 1
    @Tenfour04 but `javadoc` can't compile and run the example code nested inside Javadoc comments. See https://doc.rust-lang.org/book/ch14-02-publishing-to-crates-io.html#documentation-comments-as-tests – k314159 Jun 20 '23 at 15:04
  • 1
    Not quite the same thing, but another place to put sample code is in automated tests — they're not compiled into the final code, but they _are_ compiled and run along with the build, and so are guaranteed to be up-to-date and work. And if well-written, they should explain how to use the code being tested. (You can use a framework such as [JUnit](https://kotlinlang.org/docs/jvm-test-using-junit.html); build automation tools such as [Maven](https://kotlinlang.org/docs/maven.html) and [Gradle](https://kotlinlang.org/docs/gradle.html) can run them automatically as part of the build process.) – gidds Jun 20 '23 at 19:50

1 Answers1

2

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.

Marcus Ilgner
  • 6,935
  • 2
  • 30
  • 44