LuoJing
LuoJing

Reputation: 21

scala foreach with one augment, cannot take any operation?

I'm new to Scala, and find 'foreach' a little confused, like :

    (1 to 10).foreach(println(_)) //OK
    (1 to 10).foreach(x=>println(x+1)) //OK
    (1 to 10).foreach(println(_+1)) //ERROR

I'd know what's up in the 3rd code line. Any help is appreciated, thanks

Upvotes: 1

Views: 79

Answers (2)

Amit Prasad
Amit Prasad

Reputation: 725

There is no way to use _ for this parsing precedes type checking, so there's really no way for the compiler to read your mind here and guess what you intended consider writing the below code it's cleaner code anyway because it keeps computation separate from I/O.

(1 to 10).map(_ + 1).foreach(println)

Upvotes: 0

Raman Mishra
Raman Mishra

Reputation: 2686

(1 to 10).foreach(println(_+1))

comiler see the above expression as:

(1 to 10).foreach(println(x => x + 1))

And you want it like this:

(1 to 10).foreach(x=>println(x+1))

The placeholder syntax for anonymous functions replaces the smallest possible containing expression with a function.

Upvotes: 2

Related Questions