Question

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

Was it helpful?

Solution

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top