Scala Tutorial Scala References

Scala - Comments



The Comments are added in programming code with the purpose of making the code easier to understand. It makes the code more readable and hence easier to update the code later. Comments are ignored by the compiler while running the code. In Scala, there are three ways of putting a comment.

  • Single line comment
  • Multi-line comment
  • Documentation comment

Single line Comment

It starts with // and ends with the end of that line. Anything after // to the end of the line is a single line comment and will be ignored by the compiler.

Syntax

//single line comment.
statements; //single line comment.

Example:

The example below illustrates how to use single line comments in a Scala code. The compiler ignores the comments while compiling the code.

// first line comment
object MainObject {
  // second line comment
  def main(args: Array[String]) {
    println("Hello, world!") // third line comment 
  }
}

The output of the above code will be:

Hello World!

Multi-line Comment

It starts with /* and ends with */. Anything between /* and */ is a block comment and will be ignored by compiler.

Syntax

/*block 
comment.*/
statements; /*block comment.*/ statements;

Example:

The example below describes how to use multiple line comments in a Scala code which is ignored by the compiler while compiling the code.

object MainObject {
  /*first 
    multi-line comment. */  
   
  def main(args: Array[String]) {
    println(/*second multi-line comment.*/"Hello, world!")
    
    /*third multi-line comment. */ 
  }
}

The output of the above code will be:

Hello World!

Documentation Comment

A documentation comment is used for quick documentation lookup. These comments are used to document the source code by the compiler. The syntax for creating a documentation comment is given below:

Syntax

/**Documentation comment start
*
*tags can be used in order to specify 
*a parameter or method or heading
*HTML tags can also be used 
*such as <h1>, <h2>, and <p> etc.
*
*Documentation comment ends*/

Example:

The example below describes how to use documentation comment in a Scala program.

object MainObject {
  def main(args: Array[String]) {
    println("Documentation comments below")
    
    /** 
    * <h2>AlphaCodingSkills</h2> 
    * Scala Tutorial
    * 
    */
  }
}

The output of the above code will be:

Documentation comments below