Using "case" in PairRDDFunctions.reduceByKey ()

This is the syntax of the method. reduceByKey

def reduceByKey(func: (V, V) ⇒ V): RDD[(K, V)] 

In the word counting program that I practice, I see this code,

val counts = words.map(word => (word, 1)).reduceByKey{case (x, y) => x + y}

The application works with (x, y)instead case(x, y). What is the use casehere. I also checked the answer from @ghik here . but unable to understand

+4
source share
1 answer

Scala supports several ways to define anonymous functions. The case version is called the so-called Pattern Matching Anonymous Functions , which is more or less equivalent:

(x: Int, y: Int) => (x, y) match { case (x, y) => x + y }

and the version without caseis pretty much similar:

(x: Int, y: Int) => x + y

In this case, a simple one _ + _will be sufficient if:

val counts = words.map(word => (word, 1)).reduceByKey(_ + _)

, , , - Scala :

(x: Option[Int], y: Option[Int]) => (x, y) match {
    case (Some(xv), Some(yv)) => xv + yv
    case (Some(xv), _) => xv
    case (_, Some(yv)) => yv
    case _ => 0
} 
+3

All Articles