- Kotlin Programming By Example
- Iyanu Adelekan
- 220字
- 2021-08-27 20:00:09
Invoking functions
Functions are not executed once they are defined. In order for the code within a function to be executed, the function must be invoked. Functions can be invoked as functions, as methods, and indirectly by utilizing the invoke() and call() methods. The following shows the direct functional invocation using the function itself:
fun repeat(word: String, times: Int) {
var i = 0
while (i < times) {
println(word)
i++
}
}
fun main(args: Array<String>) {
repeat("Hello!", 5)
}
Compile and run the preceding code. The word Hello is printed on the screen five times. Hello was passed as our first value in the function and 5 as our second. As a result of this, the word and times arguments are set to hold the Hello and 5 values in our repeat function. Our while loop runs and prints our word as long as i is less than the number of times specified. i++ is used to increase the value of i by 1. i is increased by one upon each iteration of the loop. The loop stops once i is equal to 5. Hence, our word Hello will be printed five times. Compiling and running the program will give us the following output:

The other methods of function invocation will be demonstrated over the course of this book.
- 程序員面試筆試寶典
- HTML5 移動(dòng)Web開(kāi)發(fā)從入門到精通(微課精編版)
- Effective Python Penetration Testing
- 大學(xué)計(jì)算機(jī)基礎(chǔ)(第2版)(微課版)
- Reactive Android Programming
- Mastering Ext JS
- Asynchronous Android Programming(Second Edition)
- 數(shù)據(jù)結(jié)構(gòu)與算法分析(C++語(yǔ)言版)
- C和C++游戲趣味編程
- ArcGIS for Desktop Cookbook
- Hands-On GUI Programming with C++ and Qt5
- Red Hat Enterprise Linux Troubleshooting Guide
- Qt5 C++ GUI Programming Cookbook
- Maven for Eclipse
- Instant GLEW