- Kotlin Programming By Example
- Iyanu Adelekan
- 220字
- 2025-04-04 17:16:16
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.