Scala listing extra parentheses

I wrote my first 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")
}

      

Output signal

applying f1
aprintln
()
done applying f1

      

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

thank,

Jeff

+2


source to share


2 answers


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 it will be:



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

What happens here is you are executing a function f1

with a call apply

. The function f1

outputs "aprintln" and returns ()

. Then you pipe the output f1

, which is equal ()

, to another call println

. This is why you see an extra pair of paranas on the console.

The empty parentheses are of type Unit in Scala, which is equivalent to void in Java.

+5


source


Methods that will have a void return type in Java have a Unit return type in Scala. () Is how you write the value of one.



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

+2


source







All Articles