Scala: Using a for loop with embedded if statements

If you ever need to use a Scala for loop (for comprehension) with one or more embedded if statements, I hope the following example is helpful:

import scala.collection.mutable.ArrayBuffer

object Main extends App {

   * Get the contents of a text file while skipping over comment lines and
   * blank lines. This is useful when reading a data file that can have lines
   * beginning with '#', or blank lines, such as a file that looks like this:
   *   -------------------
   *   foo
   *   # this is a comment
   *   bar
   *   -------------------
  def getFileContentsWithoutCommentLines(filename: String): List[String] = {
    var lines = new ArrayBuffer[String]()
    for (line <- Source.fromFile(filename).getLines
         if !line.trim.matches("")
         if !line.trim.matches("#.*"))
      lines += line

  val lines = getFileContentsWithoutCommentLines("test.dat")


As you can see, the method I've defined in this example returns a list of strings from a given filename. The if statements embedded in the for loop keep any blank lines or comment lines from being added to the initial list of lines. Technically these if clauses are known as guards, and as you can see, that name makes sense, as the if statements guard those lines from being added to my ArrayBuffer.

(See the Comments section below for a nice improvement to the method shown.)

I haven't tested this code thoroughly yet, but I just tested it with the following sample data file contents, and at first glance it works as desired:



If you want to embed if statements into a for loop in Scala, I hope this example is helpful.