Unlike JavaDoc and KDoc, ScalaDoc has the @example
tag, which is typically used in code comments to document an example use of the API. Consider:
/**
* @constructor Create a new `Employee` by specifying their `name`, `age`,
* and `role`.
* @param name The employee’s name.
* @param age The employee’s age.
* @param role The employee’s role in the organization.
* @example {{{val e = Employee("Al", 42, "Developer")}}}
*/
from Scaladoc syntax examples (Scaladoc tags, wiki markup) by Alvin Alexander.
On the other hand, Scala has often given me the most pain regarding examples, especially code example snippets that don’t compile. Usually, such code snippets forget the necessary context, such as import
statements, required implicit
definitions, etc. It gets worse because people usually do not add the build context of necessary and sufficient dependencies for an operational Snippet Example.
What I want is a tag like @exampleSnippet
or just @snippet
that will validate, verify, and even produce the full context for an Operational Snippet. For example
/**
* @constructor Create a new `Employee` by specifying their `name`, `age`,
* and `role`.
* @param name The employee’s name.
* @param age The employee’s age.
* @param role The employee’s role in the organization.
* @snippet {{{
* import foo.bar.Employee
* val e = Employee("Al", 42, "Developer")
* }}}
*/
Where the compiler would fail/warn without the import foo.bar.Employee
line.
Furthermore, clever tools such as IntelliJ IDEA and/or GitHub Copilot would pull in additional information, such as build dependencies, and add them to the generated documentation, such as
<dependency>
<groupId>foo.bar</groupId>
<artifactId>example</artifactId>
<version>1.1.1</version>
</dependency>
Or, if I were to ‘extract’ from my IDEA GUI, and paste it in a blog somewhere, it might look something like
@snippet
import foo.bar.Employee
val e = Employee("Al", 42, "Developer")
@with
<dependency>
<groupId>foo.bar</groupId>
<artifactId>example</artifactId>
<version>1.1.1</version>
</dependency>
@from
JetBrains IntelliJ IDEA
GitHub Copilot
Note the clever promotional plugs that tells the reader that IDEA generated the snippet, so you know who/what has verified the snippet to be operational.
Bonus features would be for IDEA, ScalaDoc, etc. to have options such as extract.asHTML, or extract.asMarkdown, etc. You could give the @snippet
tag an argument such as “Employee.md” and it would produce the “Employee.md” file somewhere.
Anyway, all our lives would be better if we did not have to spend so much effort dealing with inadequate context on code snippets, by making it easier to generate operational code examples via snippets.