- Kotlin Standard Library Cookbook
- Samuel Urbanowicz
- 210字
- 2021-07-23 19:05:52
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.
- Learning Cython Programming
- Java完全自學(xué)教程
- React Native Cookbook
- AngularJS深度剖析與最佳實(shí)踐
- Microsoft System Center Orchestrator 2012 R2 Essentials
- Mastering React
- Training Systems Using Python Statistical Modeling
- JSP程序設(shè)計(jì)與案例實(shí)戰(zhàn)(慕課版)
- 青少年學(xué)Python(第2冊(cè))
- VMware vSphere 5.5 Cookbook
- Backbone.js Patterns and Best Practices
- Access 2016數(shù)據(jù)庫(kù)應(yīng)用與開發(fā):實(shí)戰(zhàn)從入門到精通(視頻教學(xué)版)
- 三步學(xué)Python
- R High Performance Programming
- FORTRAN程序設(shè)計(jì)權(quán)威指南