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

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 
主站蜘蛛池模板: 定陶县| 肥东县| 嘉荫县| 正安县| 临城县| 东平县| 融水| 阜平县| 瓦房店市| 黔西县| 泗阳县| 察雅县| 托克逊县| 百色市| 彭阳县| 孝昌县| 图木舒克市| 习水县| 襄垣县| 永城市| 巩留县| 大同县| 永嘉县| 公安县| 绵竹市| 沧源| 邢台市| 柞水县| 定州市| 贡山| 革吉县| 浦县| 郸城县| 上蔡县| 桃园县| 库尔勒市| 马山县| 温州市| 六盘水市| 武鸣县| 迁西县|