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

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.

主站蜘蛛池模板: 通化市| 吉安县| 师宗县| 通许县| 永春县| 巴彦淖尔市| 集安市| 盐山县| 定结县| 石狮市| 南郑县| 临沧市| 荣昌县| 西平县| 建瓯市| 家居| 梁平县| 依兰县| 峨眉山市| 广东省| 山阴县| 梅州市| 潞城市| 工布江达县| 临沭县| 武定县| 前郭尔| 河津市| 邹城市| 临沧市| 锡林郭勒盟| 孟津县| 清远市| 南宁市| 工布江达县| 兰坪| 曲阳县| 桐庐县| 中西区| 融水| 手游|