In the following example, we call the return value of the prefix code T, and the braces are called block. Take the pop-up desktop program selection box as an example:
var intent =Intent(Intent.ACTION_MAIN)
intent.addCategory(Intent.CATEGORY_HOME)
intent.setClassName("android","com.android.internal.app.ResolverActivity")startActivity(intent)
to sum up
let and also pass T as it to the block, the difference is that the returned result is the result of the last line of the block and T itself
run and apply pass T as this to the block, the difference is that the returned results are the result of the last line of the block and T itself
with also passes T as this to the block and returns the result of the last line of the block, the difference is that the wording is with(T)
1、let – block: (T) -> R
Calls the specified function [block] with ‘this’ value as its argument and returns its result.
Baidu Translation: Call the specified function [block] with this value as a parameter, and return the result.
Personal understanding: Pass T as it to block and return the result (T is intent, block is {} and content after let)
var intent =Intent(Intent.ACTION_MAIN)
intent.let{
//it:Intent
it.addCategory(Intent.CATEGORY_HOME)
it.setClassName("android","com.android.internal.app.ResolverActivity")startActivity(it)//这里无返回值,所以整体let也是无返回值的}.let{
//it:Unit}
2、also – block: (T) -> Unit
Calls the specified function [block] with ‘this’ value as its argument and returns this value.
Baidu Translation: Call the specified function [block] with the this value as a parameter, and return the this value.
Personal understanding: pass T as it to block and return T