2017-04-21 82 views
0

我正在使用庫函數,它爲參數minPartition使用默認參數值。我有一個包裝函數,我稱之爲庫函數。我希望包裝函數能夠工作的方式是 - 如果爲minPartition傳遞一個值,則在調用該函數時將使用此值。否則,我將使用默認值並且不傳遞參數。我如何在Scala中做到這一點?Scala - 使用默認參數值打包函數

def read(foo: String, minPartitions: Integer = ????): RDD[String] = { 
    val rdd = sc.hadoopRDD(jobConf, 
      classOf[InputFormat], 
      classOf[BytesWritable], 
      classOf[BytesWritable], 
      minPartitions // optional - default value will be used 
     ) 
} 

回答

0

您有幾種選擇:

  1. 重用的默認值。即do minPartitions =與hadoopRDD定義中的值相同
  2. 使minPartitions成爲Option [Integer],然後知道何時定義和何時定義。
  3. 使兩個版本的功能。

如果您有自己的邏輯默認值,或者真的不關心默認值是否可能在將來的某一點發生更改,則使用選項1,否則使用選項2。

0

對於可能不存在的值,Scala具有Option的概念。

Option[Int]可以是Some[Int]None。你可以在你的包裝函數中使用它。

另外...使用Scala時,除非明確要求,否則請使用Int而不是Integer。現在

...一個方式是使用模式匹配

def read(foo: String, partitionsOpt: Option[Int]): RDD[String] = { 
    partitionsOpt match { 
    case Some(partitions) => sc.hadoopRDD(
     jobConf, 
     classOf[InputFormat], 
     classOf[BytesWritable], 
     classOf[BytesWritable], 
     partitions 
    ) 
    case None => sc.hadoopRDD(
     jobConf, 
     classOf[InputFormat], 
     classOf[BytesWritable], 
     classOf[BytesWritable] 
    ) 
} 

另一種方法是mapOption,然後做一個getOrElse

def read(foo: String, partitionsOpt: Option[Int]): RDD[String] = { 
    partitionsOpt 
    .map(partitions => sc.hadoopRDD(
     jobConf, 
     classOf[InputFormat], 
     classOf[BytesWritable], 
     classOf[BytesWritable], 
     partitions 
    )) 
    .getOrElse(sc.hadoopRDD(
     jobConf, 
     classOf[InputFormat], 
     classOf[BytesWritable], 
     classOf[BytesWritable] 
    )) 
} 
+0

也許用'def read(foo:String,partitions:Int)= read(foo,Some(分區))'和'def read(foo:String)= read(foo,None)爲了方便起見,讓它更像是調用者的「默認參數」。 – PH88

0

實施例功能:

//you can directly define your default in the parameter list 
def read(minPartitions: Integer = 123): Unit { 
    println(minPartitions) 
} 

read(77) //prints out 77 
read() //prints out 123 

或者,您可以使用Option/Some/None作爲提及d在另一個答案。

實例功能:

//in this function, you must provide an Option value to second parameter 
def read(minPartitions: Option[Int]): Unit { 
    println(minPartitions.getOrElse(123)) 
} 

read(Some(77)) //prints out 77 
read(None) //prints out 123 

您也可以使用這兩個概念放在一起(定義參數類型作爲一個選項,並在參數列表中提供一個默認值)

希望這有助於! :)