You have probably heard the advice to name variables and functions after their meaning, however, sometimes this advice is difficult to follow. For this reason, many programming languages have comments to describe the meaning. But what if you need to give an example of code or refer to another function?
So let's see how documentation comments can help solve these issues in Scala with the Scaladoc tool!
Simple scaladoc
There are three types of comments in Scala:
// Single-line comment
/* Multiple lines comment
* ends with start and slash
* but is not considered documentation
*/
/** Documentation comment
* it can span several lines
* and starts with slash plus two starts
* but ends as multiple lines comment
*/
def sendMoney(amount: Int, memberId: Int): Either[String, Int] = { /* some code */ }
The documentation comments always start with /** and end with */, and affect the next function or variable in the code that comes after them.
Documenting the function
Scaladoc gives tags to provide specific detail fields in the comments. Let's see the most used tags @param, @return, and @note. If you want to explore more tags, go to this site.
/** Sends specified amount of euro to the member with specified memberId
* @param amount the integer value in € that member wants to send
* @param memberId the unique member ID in our system will accept money
* @note the amount of money to send has to be more than 10€
* @return either the error message or the balance on the sender's account
*/
def sendMoney(amount: Int, memberId: Int): Either[String, Int] = { /* some code */ }
As you can see above, we have added a doc comment for the method sendMoney, and IDEA renders info from the comment when you hover over it.
Comment in the code, code in the comment
To improve doc comments, Scaladoc provides mechanisms such as blocks of code and links. Use triple curly brackets to create a code block:
/** {{{
* val moneyToSend: Int = 100
* val recipientMemberId: Int = 42
* sendMoney(moneyToSend, recipientMemberId)
* }}}
*/
To create a link to an entity or a website, you can use double square brackets:
/**
* [[https://docs.scala-lang.org/style/scaladoc.html scaladoc guide url]]
* [[sendMoney]]
*/
Moreover, by clicking on a text next to an entity or clicking on its name in the comment, you can jump to the source code or a website.
Conclusion
In this topic, we’ve explored how to create documentation comments for Scala code and how to make it clear and concise to deliver your implementation to your colleagues. Now you can document code when the implementation that could seem complicated and not obvious at first glance.