Arun Manivannan
Arun Manivannan

Reputation: 4313

Scala first program - error

This is my first program on Scala. So, I hope I'll get the immunity of stupidity.

The code is a one line modification of a snippet from Programming in Scala.

All I am doing is

  1. reading a text file
  2. iterating the lines of the file
  3. printing the max length of the lines in the file.

That works.

Now, when I try to print each line along with the length of the line with

println (eachLine + ":" + eachLine.length)

it throws an error.

I understand from this link in SO that I am supposed to add a parenthesis somewhere. But where and why?

import scala.io.Source

class Loops {

}

object Loops{

  def main (args:Array[String]){
    printAllLines("Hello123.txt")
  }


  def printAllLines(fileName:String){

    var maxWidth=0
    var lineIterator=Source.fromFile(fileName).getLines;
    lineIterator.foreach((eachLine:String) =>
        println (eachLine + ":" + eachLine.length)
        maxWidth=maxWidth.max(eachLine.length) //Compilation ERROR at this line

    )
    Console.out.println (maxWidth)
  }

//THIS WORKS !!

def printAllLinesFor(fileName:String){

    var maxWidth=0

    for (eachLine<-Source.fromFile(fileName).getLines.toList){

        println (eachLine + ":" +eachLine.length)
        maxWidth=maxWidth.max(eachLine.length)

    }

    println (maxWidth)
 }

}

ERROR : value maxWidth is not a member of Unit //possible cause: maybe a semicolon is missing before `value maxWidth'?

Upvotes: 9

Views: 3312

Answers (3)

Frank Schmitt
Frank Schmitt

Reputation: 30775

When you add the println line, you extend the block; it had only one line before, but now it has two lines. Therefore, you have to put curly braces around it:

lineIterator.foreach((eachLine:String) => {
  println (eachLine + ":" + eachLine.length)
  maxWidth = maxWidth.max(eachLine.length) 
}

Upvotes: 1

Brian
Brian

Reputation: 20285

The foreach needs braces for a multiline function.

    lineIterator.foreach((eachLine:String) => {
        println (eachLine + ":" + eachLine.length)
        maxWidth=maxWidth.max(eachLine.length) //Compilation ERROR at this line
    })

Upvotes: 7

Brian Hsu
Brian Hsu

Reputation: 8821

Change

lineIterator.foreach((eachLine:String) =>
    println (eachLine + ":" + eachLine.length)
    maxWidth=maxWidth.max(eachLine.length) //Compilation ERROR at this line

)

to

lineIterator.foreach{ (eachLine:String) =>
    println (eachLine + ":" + eachLine.length)
    maxWidth=maxWidth.max(eachLine.length) //Compilation ERROR at this line

}

should fix this problem.

Notice the difference between foreach {...} and foreach (...), if your foreach block has multiple lines, you should use {}.

Upvotes: 10

Related Questions