Kotlin标准库里面有那么几个作用域函数(run,with,let,also,apply),下面就来简单介绍一下
第一点要了解一下,Kotlin是允许函数里面定义函数的
第二点是作用域函数怎么理解(大神忽略)。一个函数一般都有花括号{ },花括号里面就归这个函数管
第三点是run,with,let,also,apply都有返回值,返回值是该函数作用域最后一个对象
先上代码
package com.pavel.kotlindemo
/**
* 作用域函数 run with apply let also
*/
fun main(args: Array<String>) {
println("----run------")
useRun()
println("----with------")
useWith()
println("----apply------")
useApply()
println("----let------")
useLet()
println("----also------")
useAlso()
}
fun useRun(){
val string = "abcd"
string.run {
println("this is ${this}") //abcd
reversed() //调用一个反向的方法,此时该run方法返回的对象就是reversed处理的值
//this.reversed() 或者不省略this也行
}.run {
println("this is ${this}") //dcba 将上一个run方法返回的对象打印出来
length //调用对象的length此时该run方法返回的对象就是length的值
}.run {
println("this is ${this}") //4 将上一个run方法返回的对象打印出来
}
}
//下面的解释类似,ps:写多了中文在代码里面不合适
fun useWith(){
val string = "abcd"
with( with(with(string){
println("this is ${this}") //abcd
reversed()
}){
println("this is ${this}") //dcba
length
}){
println("this is $this") //4
}
}
fun useApply(){
val original = "abc"
original.apply {
println("this is ${this}") // "abc"
reversed()
}.apply {
println("this is $this") // "abc"
length
}.apply {
println("this is $this") // abc
}
}
fun useLet(){
val original = "abc"
original.let {
println("it is $it") // "abc"
it.reversed()
}.let {
println("it is $it") // "cba"
it.length
}.let {
println("it is $it") // 3
}
}
fun useAlso(){
val original = "abc"
original.also {
println("it is $it") // "abc"
it.reversed()
}.also {
println("it is $it") // "abc"
it.length
}.also {
println("it is $it") // "abc"
}
}
打印结果如下
----run------
this is abcd
this is dcba
this is 4
----with------
this is abcd
this is dcba
this is 4
----apply------
this is abc
this is abc
this is abc
----let------
it is abc
it is cba
it is 3
----also------
it is abc
it is abc
it is abc
Process finished with exit code 0
通过上面代码和打印可以看出一些异同(分析浅陋,大家可以自由总结)
先看返回值吧,返回值分两种:
第一种是返回目标对象,作用域最后对象是什么就返回什么。
第二种是返回本身对象,在作用域里面,不管对调用的对象怎么操作,返回的还是本身
其次看作用域里面的调用者,即分为it和this(this可以省略,仿佛在作用域里面就是在该对象内部)
下面一个表格归类
it | this | return(返回值) |
let | run with | 目标对象 |
also | apply | 本身 |
好像好复杂的样子,这个需要记住么?额,记住返回值就行了,因为在ide里面你往run里面写个it试试,保证飘红,同理let里面写this也飘红,ide也有提醒,截个图看看
要说在开发中如何使用
比如有个选中一个商品加入购物车
/*
加入购物车
*/
private fun addCart(){
mCurGoods?.let {
mPresenter.addCart(it.id, //ps项目采用mvp模式的
it.goodsDesc, //商品直接用let函数,在let函数里面调用presenter方法同时
//传参
it.goodsDefaultIcon,
it.goodsDefaultPrice,
)
}
}
再比如
// 普通创建Intent方法
fun createIntent(intentData: String, intentAction: String): Intent {
val intent = Intent()
intent.action = intentAction
intent.data=Uri.parse(intentData)
return intent
}
// 通过apply函数的链式调用创建Intent
fun createIntent(intentData: String, intentAction: String) =
Intent().apply { action = intentAction }
.apply { data = Uri.parse(intentData) }
好了,函数在那里,理解了想怎么用就怎么用,自己动手敲一下最上面的代码,并修改一下,可以加深理解