Search code examples
scalalambdasyntactic-sugarscala-placeholder-syntax

what is does it mean println(_)?


I have this piece of code in scala

val wordCounts = logData.flatMap(line => line.split(" ")).map(word => (word, 1)).reduceByKey((a, b) => a + b)
wordCounts.foreach(println(_))

So what does println(_) mean and what should it print?


Solution

  • As explained in the section "Placeholder Syntax for Anonymous Functions" of the Spec,

    println(_)
    

    is a shortcut for the anonymous function literal

    w => println(w)
    

    which in turn is a shortcut for something like

    (w: (String, Int)) => println(w)
    

    in this particular case.

    Therefore,

    wordCounts.foreach(println(_))
    

    simply prints every element of wordCounts.

    Note that it can also be written even shorter:

    wordCounts foreach println