标准函数with,run,apply

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
fun main() {
//常用写法
val list = listOf("apple", "banana", "orange", "pear", "grape")
val builder = StringBuilder()
builder.append("Start eat fruits\n")
for (fruit in list) {
builder.append(fruit + "\n")

}
builder.append("Ate all fruits\n")
println(builder)

//使用with作为标准函数来写
//with函数接受两个参数,第一个是任意类型的对象,第二个参数是一个lambda表达式。
//with函数会为lambda表达式中提供第一个对象的上下文
//并使用lambda表达式的最后一行代码作为返回值返回
var result = with(StringBuilder()){
append("Start eat fruits\n")
for (fruit in list) {
append(fruit + "\n")
}
append("Ate all fruits\n")
toString()
}
println(result)

//run函数
//他不能直接调用,而必须调用某个对象的run方法才行,其次run函数只接受一个lambda函数。同样的他会把最后一行表达式作为返回值。
//他与with也是很类似的,只是使用场景不太一样。
result =StringBuilder().run{
append("Start eat fruits\n")
for (fruit in list) {
append(fruit + "\n")
}
append("Ate all fruits\n")
toString()
}
println(result)


//apply函数也是与run函数极其类似,同样是需要对象调用,而且只能传入一个lambda表达式,只是他最后不用返回结果,而是自动返回调用对象本身
}

静态方法

在kotlin中,并没有绝对定义的静态函数,你可以通过定义一个单例,然后调用其中的方法。或者任意一个类通过增加他的伴生类的方法。都可以做到类似静态函数的调用方法,不用再创建实例而是直接使用。
但这根本上并不是静态方法。
如果真正的需要静态方法,可以有两种解决办法:1.注解 2.顶层方法。

  1. 注解
    在单例类或者伴生类中的方法上添加@JvmStatic的方法。这样在jvm编译时,会把他们编译为静态方法。
  2. 顶层方法
    他会直接编译为静态方法,详见:kotlin顶层方法