结论:
先执行 apply中的代码,然后返回 对象。
实验代码1:
import org.junit.Test
class MyTestUnit {
    private var num = 1
    @Test
    fun t1() {
        print(a(666).num)
    }
    fun a(n: Int) = this.apply { num = n }      //先执行了 apply 里的代码,后返回了 this
}
运行结果截图1:

实验代码2:
import org.junit.Test
class MyTestUnit {
    @Test
    fun t2() {
        print(b(888).num)
    }
    fun b(n: Int): Obj {
        val obj = Obj(1)
        return obj.apply {  //先执行了 apply 里的代码,后返回了 this
            this.num = n
        }
    }
}
data class Obj(var num: Int)
运行结果截图2:

                  
                  
                  
                  
                            
本文通过两个实验代码示例介绍了Kotlin编程语言中apply函数的使用方式。实验结果显示,apply首先执行其内部代码块,然后返回调用它的对象。这种特性常用于初始化对象时简化代码。
          
      
          
                
                
                
                
              
                
                
                
                
                
              
                
                
              
            
                  
					2万+
					
被折叠的  条评论
		 为什么被折叠?
		 
		 
		
    
  
    
  
            


            