Kotlin的一些扩展函数

Kotlin的一些扩展函数

标签(空格分隔): Android Kotlin


StandardKt.class 通用函数

repeat(Int){}

代码块执行多少次

1
2
3
repeat(2){
println("This is $it time")
}

with(obj){}

用法1:接收一个对象,在代码块中直接调用属性值赋值
用法2:接收一个对象后,可使用其属性转换成另外一个对象返回

1
2
3
4
5
6
7
8
9
10
11
12
with(TextView(context)) {
text = "Hello Kotlin"
textSize = 16f
setTextColor(android.R.color.white)
}

val imageView = with(TextView(context)) {
text = "Hello Kotlin"
textSize = 16f
setTextColor(android.R.color.white)
ImageView(context)
}

.run{}

与with类似,只不过是错用在对象上

1
2
3
4
5
6
TextView(context).run {
text = "Hello Kotlin"
textSize = 16f
setTextColor(android.R.color.white)
}

.let{}

多用于执行依据代码块,用在可能为空的对象上

1
2
3
4
val data = 1
data?.let {
println("data is not null")
}

.apply{}

对象的扩展方法,类似with

1
2
3
4
5
val textView = TextView(context).apply {
text = "Hello Kotlin"
textSize = 16
setTextColor(android.R.color.white)
}

.takeIf{}

.takeUnless{}

synchronized(Any){}

CloseableKt.class

.use{}

用于流操作,能够自动关闭流资源

1
2
3
assets.open("data.json").reader().use {
val text = it.readText()
}

closeFinally()

CollectionsKt.class

.groupBy{}

用于对集合进行分组,返回的是Map集合,key是{条件},value是集合中的对象

1
2
val list = listOf("abc", "fd", "edd", "zdc","pkj")
list.groupBy { it.first() }.forEach(::println)

.forEach{}

对集合进行遍历,array,list,map…

1
2
3
val list = listOf("abc", "fd", "edd", "zdc","pkj")
list.forEach (::println)
list.forEach{ println(it) }

.forEachIndexed{ index, T -> }

对数组进行遍历,提供角标和对象

1
2
3
list.forEachIndexed { index, s ->
println("index:$index obj:$s")
}

.filter{}

筛选指定条件的对象返回List

1
2
3
list.filter {
it.first() == 'a'
}

.reversed()

返回集合的倒序

1
list.reversed()

List.zip(List):List<Pair<T, R>>

两个集合合并,返回Pair对象

.average()

返回集合内数的平均值

.count()

返回集合的个数

…more collect