Jeff Storey
Jeff Storey

Reputation: 57192

Scala extra parentheses printout

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

Upvotes: 1

Views: 997

Answers (2)

David Crawshaw
David Crawshaw

Reputation: 10577

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.

Upvotes: 4

David Winslow
David Winslow

Reputation: 8590

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 ().

Upvotes: 2

Related Questions