高效编程
循环优化
- 使用
until
关键字
## Kotlin 提供了 `until` 关键字,用于创建不包含上限的范围(Range),增强代码可读性与安全性。
for (i in 0 until list.size) {
println("Index $i contains ${list[i]}")
}
- 使用
indices
关键字
## `indices` 属性自动生成集合的索引范围,避免手动调整或计算最后一个索引。
for (i in list.indices) {
println("Index $i contains ${list[i]}")
}
- 增强表现力:解构声明
## 利用 Kotlin 的解构声明,可以在循环中同时访问索引与元素。
for ((index, entity) in list.withIndex()) {
println("Index $index contains $entity")
}
- 使用
forEachIndexed
函数
## `forEachIndexed` 函数提供了简洁的方式对列自动产物操作。
list.forEachIndexed { index, entity ->
println("Index $index contains $entity")
}
集合去重
1、重复项去重
## 使用 `distinct` 函数去重集合中的重复项。
## 返回仅包含给定数组中不同元素的列表。
val objects = listOf("apple", "orange", "watermelon", "peach", "peach")
val uniqueObjects = objects.distinct()
println(uniqueObjects) // [apple, orange, watermelon, peach]
## 使用`Set`特性(只能包含唯一的元素),将集合转换为 `Set`
val uniqueSet = objects.toSet()
println(uniqueSet) // [apple, orange, watermelon, peach]
2、使用 distinctBy
函数定制化去重
## 如忽略大小写等特定条件来去重
val uniqueObjects = objects.distinctBy { it.lowercase() }
println(uniqueFruits) // [apple, orange, watermelon]
完全限定名
## 如在一个类中有同名的成员函数和顶层函数,可以使用完全限定名来调用顶层函数,以消除命名冲突。
## 使用完全限定名可以明确地调用特定范围内的函数或属性。
package com.wan618.demo
fun searchHotel() {
// 顶层函数实现
}
class HotelManage {
fun searchHotel() {
// 成员函数实现
}
fun findHotel() {
com.wan618.demo.searchHotel() // 调用顶层函数
}
}
Elvis 操作符 ?:
## 简化代码中对可空值的处理。
fun getValueFromApi(): String? {
return null
}
## 除返回默认值外,还可以抛出异常处理。
val result = getValueFromApi() ?: throw IllegalArgumentException("Value cannot be null")
获取代码执行时间
## 使用`measureTimeMillis` 函数来测量代码执行时间。
val time = measureTimeMillis {
getLocationInfo()
}
println("Execution took $time ms")
## 如需同时获取返回值与执行时间,可以使用 `measureTimedValue` 函数。
val (result, time) = measureTimedValue {
getLocationInfo()
}
println("Execution took $time ms and result is $result")
作用域函数(let
、run
、with
、apply
、also
)
五个函数主要的应用场景如下图所示(图片来源Google工程师)
返回值的区别
apply
和also
: 返回上下文对象自己let
、run
及with
:返回代码块结果
上下文对象引用的区别
区别:this 可以省略而 it 不可以
run
、with
及apply
:通过关键字 this 来引用上下文对象let
和also
:通过 it 来访问上下文字对象
函数原型上的区别
## `let`、`apply`、`also`:函数原型为扩展函数,它们必须需要一个对象才能调用。
User("David").apply {
sex = "man"
age = 18
}
## `with`:函数原型不是扩展函数,可直接被调用。
val names = mutableListOf("David","Mary","Paul")
wiht(names) {
val firstItem = first()
val lastItem = last()
printIn("First item:$firstItem, Iast item:$lastItem")
}
## `run`:既有扩展函数又有非扩展函数的实现方式,以上两种方式都可调用。
五个作用域函数的不同点如下表所示:
函数 | 对象引用 | 返回值 | 是否扩展函数 |
---|---|---|---|
let | it | Lambda 表达式结果 | 是 |
T.run{} | this | Lambda 表达式结果 | 是 |
run{} | - | Lambda 表达式结果 | 不是:调用无需上下文对象 |
with | this | Lambda 表达式结果 | 不是:上下文对象作为参数 |
apply | this | 上下文对象 | 是 |
also | it | 上下文对象 | 是 |