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

High-order functions

Those functions that take another function as an argument or return a function as result are called high-order functions. Consider the following example to understand it better:

    fun highOrderFunc(a:Int, validityCheckFunc:(a:Int)->Boolean) {//(1) 
      if(validityCheckFunc(a)) {//(2) 
        println("a $a is Valid") 
      } else { 
        println("a $a is Invalid") 
      } 
    } 
 
    fun main(args: Array<String>) { 
      highOrderFun(12,{ a:Int -> a.isEven()})//(3) 
      highOrderFunc(19,{ a:Int -> a.isEven()}) 
    } 

In this program, we've declared a highOrderFunc function, which will take an Int and a validityCheckFunc(Int) function. We are calling the validityCheckFunc function inside the highOrderFunc function, to check whether the value was valid or not. However, we are defining the validityCheckFunc function at runtime, while we are calling the highOrderFunc function inside the main function.

Note that the isEven function in this program is an extension function that has been defined inside the project files you got with the book.

Here is the output:

a 12 is Valid 
a 19 is Invalid 
主站蜘蛛池模板: 微博| 沙河市| 刚察县| 马尔康县| 乐都县| 南昌县| 马公市| 拉萨市| 洛扎县| 腾冲县| 浑源县| 宁安市| 和龙市| 铜梁县| 类乌齐县| 伊通| 偃师市| 井陉县| 宣城市| 普宁市| 新兴县| 威海市| 靖宇县| 织金县| 阿尔山市| 乌鲁木齐县| 正定县| 水富县| 哈尔滨市| 日照市| 通渭县| 馆陶县| 平凉市| 长阳| 蒙山县| 阜平县| 乌拉特后旗| 晋江市| 岳阳县| 安徽省| 千阳县|