tags:

views:

147

answers:

1

I'm pretty new to Scala, but I thought that one of the strengths of the language was to remove the ceremony, like paranthesis 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.

+13  A: 

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.

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

Debilski