溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

scala默認(rèn)參數(shù)值是什么

發(fā)布時(shí)間:2021-12-08 15:07:46 來源:億速云 閱讀:138 作者:iii 欄目:大數(shù)據(jù)

這篇文章主要介紹“scala默認(rèn)參數(shù)值是什么”,在日常操作中,相信很多人在scala默認(rèn)參數(shù)值是什么問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”scala默認(rèn)參數(shù)值是什么”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!

Scala具備給參數(shù)提供默認(rèn)值的能力,這樣調(diào)用者就可以忽略這些具有默認(rèn)值的參數(shù)。

這個在spark的源碼里隨處可見,比如rdd的sample函數(shù):

 /**   * Return a sampled subset of this RDD.   *   * @param withReplacement can elements be sampled multiple times (replaced when sampled out)   * @param fraction expected size of the sample as a fraction of this RDD's size   *  without replacement: probability that each element is chosen; fraction must be [0, 1]   *  with replacement: expected number of times each element is chosen; fraction must be greater   *  than or equal to 0   * @param seed seed for the random number generator   *   * @note This is NOT guaranteed to provide exactly the fraction of the count   * of the given [[RDD]].   */  def sample(      withReplacement: Boolean,      fraction: Double,      seed: Long = Utils.random.nextLong): RDD[T] = {    require(fraction >= 0,      s"Fraction must be nonnegative, but got ${fraction}")
   withScope {      require(fraction >= 0.0, "Negative fraction value: " + fraction)      if (withReplacement) {        new PartitionwiseSampledRDD[T, T](this, new PoissonSampler[T](fraction), true, seed)      } else {        new PartitionwiseSampledRDD[T, T](this, new BernoulliSampler[T](fraction), true, seed)      }    }  }

定義一個參數(shù)帶默認(rèn)值的函數(shù),很簡單,我們可以仿照上面的spark 源碼中的案例:

def log(message: String, level: String = "INFO") = println(s"$level: $message")
log("System starting")  log("User not found", "WARNING")  

上面的參數(shù)level有默認(rèn)值,所以是可選的。最后一行中傳入的參數(shù)"WARNING"重寫了默認(rèn)值"INFO"。在Java中,我們可以通過帶有可選參數(shù)的重載方法達(dá)到同樣的效果。不過,只要調(diào)用方忽略了一個參數(shù),其他參數(shù)就必須要帶名傳入。

class Point(val x: Double = 0, val y: Double = 0)
val point1 = new Point(y = 1)

這里必須帶名傳入y = 1

注意從Java代碼中調(diào)用時(shí),Scala中的默認(rèn)參數(shù)則是必填的(非可選),如:

class Point(val x: Double = 0, val y: Double = 0)

public class Main {    public static void main(String[] args) {        Point point = new Point(1);      }}

到此,關(guān)于“scala默認(rèn)參數(shù)值是什么”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識,請繼續(xù)關(guān)注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI