新聞中心
這篇文章主要介紹“scala默認(rèn)參數(shù)值是什么”,在日常操作中,相信很多人在scala默認(rèn)參數(shù)值是什么問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”scala默認(rèn)參數(shù)值是什么”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!
為雙城等地區(qū)用戶提供了全套網(wǎng)頁設(shè)計(jì)制作服務(wù),及雙城網(wǎng)站建設(shè)行業(yè)解決方案。主營業(yè)務(wù)為網(wǎng)站設(shè)計(jì)制作、成都網(wǎng)站建設(shè)、雙城網(wǎng)站設(shè)計(jì),以傳統(tǒng)方式定制建設(shè)網(wǎng)站,并提供域名空間備案等一條龍服務(wù),秉承以專業(yè)、用心的態(tài)度為用戶提供真誠的服務(wù)。我們深信只要達(dá)到每一位用戶的要求,就會(huì)得到認(rèn)可,從而選擇與我們長期合作。這樣,我們也可以走得更遠(yuǎn)!
Scala具備給參數(shù)提供默認(rèn)值的能力,這樣調(diào)用者就可以忽略這些具有默認(rèn)值的參數(shù)。
這個(gè)在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)
}
}
}
定義一個(gè)參數(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)用方忽略了一個(gè)參數(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)注創(chuàng)新互聯(lián)網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!
名稱欄目:scala默認(rèn)參數(shù)值是什么
當(dāng)前路徑:http://www.dlmjj.cn/article/gieeps.html