views:

68

answers:

2

Hi,

I wrote my first sample scala program and it looks like this:

def main(args: Array[String]) {  
    def f1 = println("aprintln")
    println("applying f1")
    println((f1 _).apply)
    println("done applying f1")
}

The output is

applying f1
aprintln
()
done applying f1

Can someone explain why the extra () appears? I thought just aprintln would appear.

thanks,

Jeff

+1  A: 

Methods that would have a void return type in Java have a return type of Unit in Scala. () is how you write the value of unit.

In your code, f1 calls println directly. So when you call f1 and pass its result to println, you both print a string in the body of f1, and print its result, which is tostring'ed as ().

David Winslow
Makes sense and is in agreement with the other answer. thank you.
Jeff Storey
+3  A: 

This will fix the problem:

def main(args: Array[String]) {         
    def f1 = println("aprintln")
    println("applying f1")
    (f1 _).apply
    println("done applying f1")
}

And so will this:

def main(args: Array[String]) {         
    def f1 = "aprintln"
    println("applying f1")
    println((f1 _).apply)
    println("done applying f1")
}

What's going on here is you are executing the function f1 with the call to apply. The function f1 prints out 'aprintln', and returns (). You then pass the output of f1, which is (), to another call to println. That's why you see an extra pair of parans on the console.

The empty parentheses have the type Unit in Scala, which is equivalent to void in Java.

David Crawshaw
Ah, yes, very silly of me. I didn't think about that since the Java compiler wouldn't have let me do that. Thank you.
Jeff Storey