Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I write println "Hello world" in Scala?

Tags:

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.

like image 567
mranders Avatar asked Sep 01 '10 11:09

mranders


2 Answers

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.

like image 62
Debilski Avatar answered Oct 01 '22 11:10

Debilski


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

like image 22
Rahel Lüthy Avatar answered Oct 01 '22 12:10

Rahel Lüthy