高阶函数
关心函数的返回值
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