官术网_书友最值得收藏!

Declaring adjustable functions with default parameters

When creating new functions, we often need to allow some of their parameters to be optional. This forces us to use method overloading to create multiple function declarations with the same name but different sets of arguments related to different use cases and scenarios. Usually, under the hood, each variant of the function is calling the base function with the default implementation. Let's consider a simple example of a function that calculates a displacement of an object moving with a constant acceleration rate:

fun calculateDisplacement(initialSpeed: Float, 
acceleration: Float,
duration: Long): Double =
initialSpeed * duration + 0.5 * acceleration * duration * duration

We might also need to provide a displacement calculation for the scenario where the initial speed of the object is always equal to zero. In such a case, we would end up with overloading the basic function in the following manner:

fun calculateDisplacement(acceleration: Float, duration: Long): Double = calculateDisplacement(0f, acceleration, duration)

However, Kotlin allows you to reduce multiple declarations and to handle a number of different use cases with a single function having optional parameters. In this recipe, we are going to design an adjustable version of the calculateDisplacement() function with an optional initialSpeed: Float parameter.

主站蜘蛛池模板: 白水县| 香港| 海盐县| 莱州市| 西宁市| 临湘市| 阆中市| 沁源县| 横峰县| 田林县| 余干县| 突泉县| 贺州市| 喜德县| 巴彦淖尔市| 邵阳县| 水城县| 长治市| 龙井市| 清新县| 洛南县| 凤翔县| 南岸区| 自治县| 神农架林区| 柘荣县| 砀山县| 磐石市| 宜春市| 河间市| 衡水市| 潮州市| 盘锦市| 西乡县| 铜陵市| 尖扎县| 新乡市| 新干县| 观塘区| 专栏| 稻城县|