4

I wonder, why can't I compile this one:

class MyClass{
  override def toString = "123:" + if (true) "456" else "789"
  //error:  illegal start of simple expression
}

2 Answers 2

10

Try this:

override def toString = "123:" + (if (true) "456" else "789")
Sign up to request clarification or add additional context in comments.

2 Comments

It was useful to me when I realized that "simple expression" is in contrast to "expr": github.com/scala/scala-dist/blob/master/documentation/src/… It clarifies similar questions like why can't I (Console println throw new RuntimeException).
Yeah, there a few precedence issues regarding these expressions. Check this out docs.scala-lang.org/sips/pending/uncluttering-control.html, maybe in the near future...
0

pedrofurla is right. With your expression the compiler tries to mix the string with the if and fails. Using parenthesis you eliminate ambiguity in your expressions.

class MyClass{
   override def toString = "123:" + (if (true) "456" else "789")
}

I found this simple online service where you can test your scala expressions: http://www.simplyscala.com/

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.