val res =with(obj){//这里是obj对象的上下文"value"//这里是with函数的返回值}
with函数的作用.假如现在有个需求让吃完所有的水果并且将结果打印出来,代码可以这样写
funmain(){doSomething()}fundoSomething(){val list = listOf<String>("Apple","Banana","Pear")val sb =StringBuilder()
sb.append("Start eating fruits.\n")for(fruits in list){
sb.append(fruits).append("\n")}
sb.append("Ate all fruits.")val res = sb.toString()println(res)}
funwithTest(){val list = listOf<String>("Apple","Banana","Pear")val res =with(StringBuilder()){append("Start eating fruits.\n")for(fruits in list){append(fruits)append("\n")}append("Ate all fruits.")toString()//最后一行就是函数的返回值}println(res)}
run函数
run函数和with函数基本类似,区别就是,run函数不能直接调用,需要在某个对象的基础上进行调用
其次run函数只接受一个Lambda参数,并且在Lambda表达式中提供调用对象的上下文.
其他和with函数都是一样的
使用run函数完成上述需求的实例
funrunTest(){val list = listOf<String>("Apple","Banana","Pear")//将StringBuilder调出来,用来调用run函数val res =StringBuilder().run{append("Start eating fruits.\n")for(fruits in list){append(fruits)append("\n")}append("Ate all fruits.")toString()}println(res)}
apply函数
apply函数和run函数基本一样,就是apply函数不能指定返回值,只能返回调用调用者的本身
apply函数实例
funapplyTest(){val list = listOf<String>("Apple","Banana","Pear")val res =StringBuilder().apply{append("Start eating fruits.\n")for(fruits in list){append(fruits)append("\n")}append("Ate all fruits.")}println(res.toString())}