0

I was wondering the correct way to format a situation such as this, where I have a def, a foreach and an if clause all nested, requiring braces.

Currently I find it hard to read, and there is no obvious place to put the 'x =>' bit. Thank you.

def getAnswer(): String =
{
  var sum = 0
  (0 until 1000).foreach 
  { x => 
    if (x % 3 == 0 || x % 5 == 0)
    {
      sum += x
    }
  }
  sum.toString
}
  • This is probably off-topic for the Programmers Stack Exchange, it would be more appropriate on StackOverflow. – Jay Elston Mar 6 '14 at 19:53
  • @JayElston I disagree: SO is more about making code work or understanding code, whereas this is a whiteboard-style conceptual question that's a good fit here. If it were off topic, then because it would be purely opinion-based – but that is not the case here as an authoritative style guide exists which addresses these options. – amon Mar 6 '14 at 20:00
7

Scala has an official style guide which recommends putting opening braces on the same line, not on a line of their own. Parameters should also be on the first line.

def getAnswer(): String = {
  var sum = 0
  (0 until 1000).foreach { x => 
    if (x % 3 == 0 || x % 5 == 0) {
      sum += x
    }
  }
  sum.toString
}

In your specific case, you should probably remove most of your braces, as all but the outermost are not needed (also, filter would be idiomatic here):

def getAnswer(): String = {
  var sum = 0
  0 until 1000 filter (x => x % 3 == 0 || x % 5 == 0) foreach (x => sum += x)
  sum.toString
}
  • You're still putting the x => on the same line as the opening brace. Is that in the style guide too? It would be highly unorthodox. Normally the opening brace is the last thing on the line, if you're using Egyptian Brackets. – Robert Harvey Mar 6 '14 at 19:24
  • @RobertHarvey yes, see my update for the link – amon Mar 6 '14 at 19:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.