4

This was a fairly hard bug to find in my code but once i found it i was surprised the compiler didn't catch it or understand why it was valid.

val my_string =
    "abc" +
    "def"
    "ghi"

The value of my_string ended up being "abcdef" since i missed the + sign after "def". Why didn't the compiler complain and what happened to "ghi"?

2
  • will now enclose multi-line strings in triple quotes to avoid future bugs Commented Nov 10, 2010 at 16:47
  • 3
    A common practice is to wrap all tokens of an expression inside parenthesis to avoid such issues, e.g., val my_string = ( ... ) Commented Nov 10, 2010 at 20:27

2 Answers 2

10

The code is valid because "ghi" is a valid expression on its own.

If this is inside a function (and not followed by anything else) then "ghi" is the return value of that function. Otherwise it's just ignored (like if you'd written 42 + 23 on a line on its own).

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

3 Comments

it's being declared as an instance variable inside my class. I guess you wouldn't be able to reference it, it would just execute and move on?
@Mark: Any expression in the class body is considered part of the constructor. So every time an instance of your class is created the expressions "ghi" is evaluated (which doesn't have any effect at all).
that's right! i remember reading that now / i appreciate it, thanks
1

"ghi" is just an expression of type String, why should the compiler complain?

2 Comments

because in java it is not statment so it is logical to assume that compiler would fail if you came from java world
@yura: yes, but this is not Java, and you should not make the mistake of looking at Scala as Java with some "extensions". I find that one of the most useful mind shifts if you're learning Scala, is to understand that everything is just an expression that evaluates to something.

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.