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

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 
主站蜘蛛池模板: 南漳县| 亚东县| 毕节市| 安西县| 霞浦县| 禄丰县| 蒙城县| 中宁县| 阿鲁科尔沁旗| 安达市| 略阳县| 桐柏县| 民勤县| 开原市| 泰安市| 托里县| 平山县| 沈阳市| 池州市| 县级市| 广西| 凤阳县| 百色市| 太湖县| 光泽县| 长葛市| 宜章县| 连州市| 宾川县| 玛多县| 资阳市| 毕节市| 武穴市| 仙居县| 定襄县| 油尖旺区| 文山县| 涟源市| 湘西| 芦山县| 利辛县|