Higher-order functions in Kotlin notes

Higher order function

definition

A higher-order function is a function that takes another function as a parameter or return value . Any function that takes a lambda or a function reference as a parameter, or a function whose return value is a lambda or a function reference, or a function that satisfies both is a higher-order function

Function type

The function type syntax is as follows: To
Insert picture description here
declare the function type, you need to put the function parameter type in parentheses, followed by an arrow and the return type of the function

Examples are as follows:

// 有两个Int型参数和Int型返回值的函数
val sum:(Int,Int) -> Int={
    
    x,y ->x+y}

// 没有参数和返回值的函数
val action:()->Unit ={
    
    println(12)}

Note: When declaring an ordinary function, the return value of the Unit type can be omitted, but a function type declaration always requires an explicit return type, so Unit cannot be omitted in this scenario

The return value of the function may be null type and function type can be empty case variable

// 函数类型的返回值为可空
var can :(Int,Int)-> Int?={
    
    null}

//函数类型的可空变量
var f:((Int,Int) -> Int)?=null

Function type as parameter

fun numResult(operation :(Int,Int)->Int){
    
    
    // 调用函数类型的参数
   val result=opration(2,3)
   println("The result is $result")
}

>>>> numResult{
    
    a,b -> a + b}
The result is 5

Function type as the return type of the function

To return a function, you need to write a return expression, followed by a lambda, a member reference, or other function type expressions, such as a (function type) local variable

data class Person(
   val firstName :String,
   val lastName :String,
   val phoneName :String?
)

class ContactListFilters{
    
    
  var prefix:String=""
  var onlyWithPhoneNumber:Boolean =false
   
  // 声明一个返回函数的函数
  fun getPredicate(): (Person) -> Boolean {
    
    
     val startsWithPrefix={
    
    p : Person -> p.firstName.startWith(prefix) || p.lastName.startsWith(prefix)}
     if(!onlyWithPhoneNumber){
    
    
         // 返回一个函数类型的变量
        return  startsWithPrefix
     }
     // 返回一个lambda
     return {
    
    startsWithPrefix(it) && it.phoneNumber !=null}
  }
}

>>>>> val contacts=listof(Person("mike","Li","125"),Person("marry","Zhao",null))
val  filters=ContactListFilters()
with(filters){
    
    
  prefix="Li"
  onlyWithPhoneNumber=true
}
println(contacts.filter(filters.getPredicate()))

Guess you like

Origin blog.csdn.net/xufei5789651/article/details/103049242