I'm pretty new to Scala, but I thought that one of the strengths of the language was to remove the ceremony, like parenthesis and dots, that exists in for instance Java. So I was pretty confused when I discovered that I can write for instance
str1 equals str2
but not
println "Hello world"
I have surmised that it has something to do with that the first example has three "parts", but the second has only two, but I'm struggling to understand why it is so.
When there are only two parts, the expression is seen as method invocation. I.e. the only possibility for
println "Hello, world"
would be
println."Hello, world"
which of course does not make much sense here. (***** see below for an addition)
If you like, however, you can write Console println "Hello, World"
to resolve the ambiguity.
It doesn’t look that ambigus in the string example, a string could hardly be a method name, but think of the following:
class B val b = new B object A { def apply(myB: B) { print("apply") } def b { print("b") } }
Now, when writing A b
, what do I get. How should it be interpreted? It turns out that:
A b // "b" A.b // "b" A(b) // apply
So, there is a clear rule what to do in a two part expression. (I hope nobody starts splitting hairs about apply
and real method invocation…)
Addition
With the advent of dynamic classes, you can toy around a little and define the following
object println extends Dynamic { def typed[T] = asInstanceOf[T] def applyDynamic(name: String)(args: Any*) = Console.println(name) }
And now look!, no parentheses:
println `Hello, world` // prints, "Hello, world"
Of course, please don’t do that in front of children or in real-life code.
You could rewrite your second example with three "parts", in which case it would compile without parentheses:
Predef println "Hello world"
(Just for illustration purposes -- @Debilski's answer is perfect!)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With