- Kotlin for Enterprise Applications using Java EE
- Raghavendra Rao K
- 223字
- 2021-06-10 18:49:20
varargs and spread
Kotlin supports a variable number of arguments. vararg is the keyword that is used for a variable number of arguments. Using vararg, we can pass multiple arguments to a function.
Let's see an example of 7a_VarArgs.kts:
fun findMaxNumber(vararg numbers : Int) =
numbers.reduce { max , e -> if(max > e) max else e }
println(findMaxNumber(1,2,3,4))
The output is as follows:
The findMaxNumber() function takes a variable number of arguments and finds the maximum. We invoked reduce on the numbers and wrote a lambda expression. In Kotlin, a lambda is specified using curly braces.
If we have an array of numbers, we can invoke the findMaxNumber() function using the spread operator without changing the function argument type.
Consider the following code for 7b_Spread.kts:
fun findMaxNumber(vararg numbers : Int) =
numbers.reduce { max , e -> if(max > e) max else e }
val numberArray = intArrayOf(25,50,75,100)
println(findMaxNumber(*numberArray))
The output is as follows:
Note that * acts as a spread operator here. We can combine this with discrete values, as shown in the following 7c_Spread file.
Consider the code for 7c_Spread.kts:
fun findMaxNumber(vararg numbers : Int) =
numbers.reduce { max , e -> if(max > e) max else e }
val numberArray = intArrayOf(25,50,75,100)
println(findMaxNumber(4,5,*numberArray,200, 10))
The output is as follows:
- Vue.js前端開發(fā)基礎(chǔ)與項(xiàng)目實(shí)戰(zhàn)
- 面向?qū)ο蟪绦蛟O(shè)計(jì)(Java版)
- ExtJS高級(jí)程序設(shè)計(jì)
- 西門子S7-200 SMART PLC編程從入門到實(shí)踐
- HTML+CSS+JavaScript網(wǎng)頁設(shè)計(jì)從入門到精通 (清華社"視頻大講堂"大系·網(wǎng)絡(luò)開發(fā)視頻大講堂)
- Learning Modular Java Programming
- 3D Printing Designs:The Sun Puzzle
- INSTANT LESS CSS Preprocessor How-to
- PHP面試一戰(zhàn)到底
- TensorFlow程序設(shè)計(jì)
- Programming MapReduce with Scalding
- Web 2.0策略指南
- Building RESTful Web Services with PHP 7
- Visual C++.NET(2008)典型案例
- Learning Spark SQL