kotlin 方法引用作为参数传入

package weather.qf.kotlin_coroutine_demo

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import kotlinx.coroutines.*
//****可以执行****
class QueryBjClass {
    suspend fun searchCity(keyword: String){
        
        println("+++")

    }
}

fun
//        CoroutineScope.
        searchCity(keyword: String){
    
    println("+++")

}
fun main()= runBlocking {
    //第一、二、四行这样引用searchCity不会执行,也没报错  方法引用::searchCity放在lambda的方法体内,不会执行,需要在参数位置上直接引用 或在lambda的方法体内调用方法
    //第三行才会执行
    //第五行直接引用::searchCity找不到launch方法
    launch("北京", { -> QueryBjClass::searchCity })
    launch("北京", {str-> QueryBjClass()::searchCity  })
    launch("北京", {str-> QueryBjClass().searchCity(str)  })
    launch("北京", {str-> ::searchCity  })
    launch("北京", {str-> searchCity(str) })
    launch("北京",
//        CoroutineScope::
    ::searchCity  )  //找不到launch方法,方法不匹配.把launch中的接收者类型去掉,或给顶级的searchCity变成CoroutineScope的扩展函数,传入时也加上CoroutineScope,就可以了
    launch("北京", { -> println("str")  })
    launch("北京", { str ->
        println("str")
        println(str)
    })
}
@JvmName("launch1")
fun launch(keyword: String, block: suspend
//CoroutineScope.
    (String) -> Unit){
//    GlobalScope.launch
    runBlocking{
        withContext(Dispatchers.IO){
            println("11+==")
            //就像Java 反射 Method调用一样,传入对象与方法参数,没有方法参数和接收者类型可以直接block()调用,没有接收者类型,就不要传this
            //   或者     block().invoke(this)  也可以
            //根据情况调用:block(keyword)等价于block.invoke(keyword)  , block()  、  block.invoke(this)  、  block.invoke(this,keyword) 有接收者类型,并且使用invoke调用,必须传入this
//            block.invoke(
//                this,
//                keyword)
//                    .invoke(this)
            block(keyword)
            println("12+==")
        }
    }
}
fun launch(keyword: String, block: suspend CoroutineScope.() -> Unit){
//    GlobalScope.launch
    runBlocking{
        withContext(Dispatchers.IO){
            println("21+==")
            block()
//           或者     block().invoke(this)  也可以
            println("23+==")
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值