Kotlin中的高阶函数的使用

高阶函数

  • 函数的参数是一个函数

关心函数的返回值

  • 参数为一个函数,并关心其返回值
class FunctionTest {
    
    

    @Test
    fun test() {
    
    
        application()
        println(ABTest.isNewVip.invoke())
    }

    private fun application() {
    
    
        ABTest.isNewVip = {
    
    
            println("application")
            true
        }
    }

}

object ABTest {
    
    
    var isNewVip: (() -> Boolean) = {
    
     false }
}
application
true
data class ApiResponse<T>(
        val error: Boolean,
        val results: List<T>
)

data class ApiResult<T>(val success: Boolean, val data: T) {
    
    
    companion object {
    
    
        inline fun <T> create(request: () -> ApiResponse<T>): List<T> {
    
    
            return try {
    
    
                val response = request.invoke()
                response.results
            } catch (e: Exception) {
    
    
                if (e is UnknownHostException) {
    
    
                    ToastUtils.showShort("连接服务器失败")
                } else if (e is InterruptedIOException) {
    
    
                    ToastUtils.showShort("连接服务器超时")
                } else if (e is JSONException || e is JsonParseException || e is ParseException) {
    
    
                    ToastUtils.showShort("数据解析出错")
                } else {
    
    
                    ToastUtils.showShort("未知的网络错误")
                }
                Log.e("ApiResult", "create: " + e.message)
                emptyList()
            }
        }
    }
}

关心函数的参数

  • 参数是一个函数,关心函数的参数
package com.zhangyu.editor

import org.junit.Test

class FunctionTest {
    
    

    @Test
    fun test() {
    
    
        application()
        //
        create {
    
     it1, it2 ->
            println(3)
            println(it1)
            println(it2)
            6
        }
    }

    private fun application() {
    
    
        println(1)
        val a = 1
        val b = 2
        ABTest.isNewVip = {
    
     a > b }
    }

    private fun create(request: (param1: Int, param2: Int) -> Int) {
    
    
        println(2)
        println(request.invoke(4,5))
        println(7)
    }

}

object ABTest {
    
    
    var isNewVip: (() -> Boolean) = {
    
     false }
}

1
2
3
4
5
6
7

猜你喜欢

转载自blog.csdn.net/yu540135101/article/details/113446118