簡體   English   中英

在PairRDDFunctions.reduceByKey()中使用'case'

[英]Using 'case' in PairRDDFunctions.reduceByKey()

這是方法reduceByKey的語法

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

在我練習的字數統計程序中,我看到這段代碼,

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

該應用程序使用(x, y)而不是case(x, y) 這里的case什么用處。 我也在這里檢查了@ghik的答案。 但不能理解

Scala支持多種定義匿名函數的方法。 “case”版本是所謂的模式匹配匿名函數 ,它或多或少等同於:

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

而沒有case版本幾乎是它的樣子:

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

在這種情況下,簡單的_ + _就足夠了:

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
} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM