这篇文章主要介绍“scala默认参数值是什么”,在日常操作中,相信很多人在scala默认参数值是什么问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”scala默认参数值是什么”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
Scala具备给参数提供默认值的能力,这样调用者就可以忽略这些具有默认值的参数。
这个在spark的源码里随处可见,比如rdd的sample函数:
/** * 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) } } }
定义一个参数带默认值的函数,很简单,我们可以仿照上面的spark 源码中的案例:
def log(message: String, level: String = "INFO") = println(s"$level: $message")log("System starting") log("User not found", "WARNING")
上面的参数level有默认值,所以是可选的。最后一行中传入的参数"WARNING"
重写了默认值"INFO"
。在Java中,我们可以通过带有可选参数的重载方法达到同样的效果。不过,只要调用方忽略了一个参数,其他参数就必须要带名传入。
class Point(val x: Double = 0, val y: Double = 0)val point1 = new Point(y = 1)
这里必须带名传入y = 1
。
注意从Java代码中调用时,Scala中的默认参数则是必填的(非可选),如:
class Point(val x: Double = 0, val y: Double = 0)public class Main { public static void main(String[] args) { Point point = new Point(1); }}
到此,关于“scala默认参数值是什么”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://my.oschina.net/u/4590259/blog/4409737