user3248346
user3248346

Reputation:

Confused about function literals

Scala newbie here.

I have a Set defined and declared as follows:

var g = Set(1,2,3)

Now I want to print out each element of the Set as follows using a function literal:

scala> g.foreach(s => println(s))
1
2
3

All is good.

I can be more concise so I do this:

scala> g.foreach(println)
1
2
3

All is good.

Now when I do this:

scala> g.foreach(println())
<console>:9: error: type mismatch;
 found   : Unit
 required: Int => ?
              g.foreach(println())

Why do this fail? To me (a newbie), it seems like it is the equivalent of g.foreach(println). Please can someone explain the error.

Upvotes: 0

Views: 182

Answers (3)

Vladimir Matveev
Vladimir Matveev

Reputation: 127711

When you pass function literal or a function directly, like in your first two examples, you do not invoke that function immediately. However, in your last example you do immediately invoke it, because println() is exactly a syntax for calling functions and methods. Because println() result type is Unit, you're in fact passing a value of type Unit into a method which expects a value of type (String) => Unit, and of course these are different values, so the compiler shows an error.

Upvotes: 4

Lee
Lee

Reputation: 144106

The function println () prints a newline to standard output and has a return type Unit e.g.

val u: Unit = println()

The foreach function requires as its argument a function to apply to each element of the collection. println is such a function, which displays each argument, while Unit is not a function.

Upvotes: 0

user908853
user908853

Reputation:

It is not the equivalent, when you pass println, you are passing a function that yet needs to be applied on each member of the set, on the other hand, passing println() is passing a Unit, but foreach needs to be passed a function that takes whatever the type of the set is and does something with it.

Upvotes: 2

Related Questions