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

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 
主站蜘蛛池模板: 垫江县| 深水埗区| 平昌县| 贺州市| 略阳县| 桃园县| 漳浦县| 沈阳市| 光山县| 郑州市| 阳城县| 钟山县| 临猗县| 利津县| 文水县| 昌江| 两当县| 芜湖市| 海口市| 东城区| 滁州市| 宜丰县| 乐都县| 咸宁市| 乌苏市| 高邮市| 霍邱县| 五指山市| 万源市| 延长县| 志丹县| 筠连县| 佛学| 靖江市| 东辽县| 乌兰察布市| 南京市| 九台市| 静乐县| 三台县| 扬州市|