9

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'?

0

3 Answers 3

10

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 {}.

Sign up to request clarification or add additional context in comments.

Comments

7

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
    })

Comments

1

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) 
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.