kotlin备忘录速记

记录一些速查的kotlin高频函数和API,省的太久不写忘了

定义约定

常量
1
val Name : Type = initVal
变量

var Name : Type = initVal

函数
1
2
3
(override... 修饰符) fun Name (para:paraType = deafultVal) : return Type{

}
可为null
1
2
3
4
5
6
7
8
9
val Name : Type? = initVal/null
// 如果显式设置了类型,只有类型名后加?才可设为null

Name!!.member // !!后缀表示断言该量一定不为null
// 条件表达式也可以智能推断是否为null
//

val Name : Type = null?:deafultVal
// ?:是 Elvis运算符,当运算符左侧的值为null时返回运算符右侧设置的默认值
1
2
3
4
5
6
7
8
9
10
11
// 主构造函数,参数前加val/var则无需在类主体中再次定义该成员
// open说明该类可被继承
// 父类的构造函数的调用接在主构造函数后
// 实现的接口接在父构造函数后,用逗号链接
(open) class Name(val member:Type,...) : FatherClassConstructor(para),interface{
val member = initVal
get()
set()
// get,set为内置关键字,可选,紧跟在对应成员后
constructor(para):this(para)//重载构造函数,如果需要给主构造函数补参数
}
修饰符
1
2
3
4
5
6
class ClassName(){
public val member1 // 默认修饰符,可以任意访问
private val member2 // 仅可在类内部访问
protected val member3 // 只能被子类访问
internal val member4 // 只能在同一文件中被访问
}
定义委托
1
2
3
var Name by delegateObject
// 把变量的getter和setter委托给自定义类(即重载变量的getter和setter)
// 委托类需实现ReadWriteProperty<Any?, Type>或ReadOnlyProperty<Any?>接口
储存函数
1
2
3
4
5
6
7
fun myFunc(){
...
}

fun main(){
val FunctionVal = ::myFunc // 将函数作为变量存储须在函数名前加::
}
lambda
1
2
3
4
5
6
7
8
9
10
11
12
13
14
val Name:(paraType) -> returnType = {
para -> body


// 后置lambda语法
// myFunc(Int,Int,(Int,Int)->Int)
// 当函数的最后一个参数是lambda时可以在调用函数时直接把lambda写在调用后面
myFunc(1,2){
x,y -> x+y
}

}

val
函数数据类型约定
1
(paraType1,ParaType2...) -> returnType
泛型(模板类)约定
1
2
3
4
5
class tempClass<T>(val para:Type,val tempPara:T){

}
val Name = tempClass<Int>(para1,2)

枚举类约定
1
2
3
4
5
6
7

enum class Name{
enumName1,enumName2
}

val enumNum:Name = Name.enumName1

数据类约定
1
2
3
4
data class Name(val value1:Type,val value2:Type...){
}
//专用于处理数据的类,没有任何执行操作的方法
//编译器会自动实现equals(),hashCode(),toString(),componentN():component1()、component2() ... ,copy()这些方法
单例对象约定
1
2
3
object Name{
}
和类相同,但是全局只存在一个实例,且无须自己创建,必须在定义时就初始化
定义拓展属性
1
2
3
4
5
6
7
8

val typeName.extendPropertyName : dataType
get()//为拓展属性设置getter

fun typeName.extendFunctionName(para...) : returnType{

}
//拓展属性只能读取不能写入
接口
1
2
3
4
5
interface InterfaceName{
val member:Type
fun function(para):return Type
//接口只声明不实现,继承接口的类必须实现接口声明的所有内容(override)
}

分支约定

if-else
1
2
3
4
5
6
if(condition){

}
else{

}
when
1
2
3
4
5
6
when(para){
condition1 -> {body1}
condition2 -> {body2}
.....

}

特殊约定

分支,lambda返回值

分支,lambda的最后一个表达式的值会作为整个结构的返回值

1
2
3
4
5
6
7
8
9
x= if(true){
"1"
}
else{
"0"
}
// x="1"

x={2} // x=2
字符串中嵌入表达式
1
"x= ${x.value}"

使用${}向字符串嵌入表达式

帮手函数

repeat(times: Int, action: (Int) -> Unit)

重复执行某一操作,传入一个lambda,有一个从0开始的迭代器参数

1
2
3
4
5
6
7
8
repeat(5){
it -> println(it)
}
// 0
// 1
// 2
// 3
// 4
let()
1
2
3
4
5
6
7
8
9
10
11
//before let
println(Obj.member1)
println(Obj.member2)
println(Obj.member3)

// after let
Obj.let{
println(it.member1)
println(it.member2)
println(it.member3)
}

let后接一个lambda函数,可以把let前的对象用it关键字简写
lambda 最后一条语句的返回值会被作为let的返回值

apply()
1
2
3
4
5
6
7
8
9
10
11
Obj.apply{
this.member= ....
this.initFunc()
}
// hint : 可以实现链式调用
Obj.apply{
member1 = ...
}.apply{
member2 = ...
}.....

对目标对象做一系列操作,通过this访问目标对象,返回操作完的目标对象

forEach(action: (T) -> Unit)

forEach传入一个lambda,对目标集(List,set…)中的每一个元素执行该lambda

1
2
3
4
5
val test1=setOf(1,2,3,4,5)
test1.forEach{
println(it)
}
// 1,2,3,4,5

数据管理

数组 array
1
2
3
val array = arrayOf<Type>(elem1,elem2,....) // 使用arrayOf初始化,单一类型,长度不可变
println(array[0]) // 使用下标访问
val arrry12 = array1+array2 //拼接两个数组
列表(可变长数组) list
1
2
3
4
5
6
7
8
9
10
11
12
13
14
val aList=listOf(1,2,true,"123") // 使用listOf初始化,可以混合类型,不可修改元素,不可增减元素
println(aList.size) // 查询长度
println(aList[0]) // 下标访问
println(aList.indexOf("123)) // 3 ,若未找到返回-1
for (elem in aList) {
// 使用 for 遍历
}
anotherList=mutableListOf(1,2,true,"123") // 可修改的列表
anotherList.add("4") // [1,2,true,"123","4"] //向末尾添加元素
anotherList.add(2,"4") // [1,2,"4",true,"123","4"] // 向中间插入
anotherList.removeAt(0) // [2,"4",true,"123","4"] // 按下标删除
anotherList.remove("123") // [2,"4",true,"4"] // 按值删除
anotherList.contains(2) //查询是否存在
2 in anotherList // 前者的另一写法
集合 set

Set / mutableSet 同样 不可修/可修

1
2
3
val aSet=mutableSetOf("123",true,32)
// 有add,remove,contain,size,没有下标操作
// 基于每个类的hashCode()实现
映射 map

Map / mutableMap 同样 不可修/可修

1
2
3
4
5
6
7
val aMap=mutableMapOf(
"cake" to 10,
"cookie" to 5,
true to 22
)
println(aMap["cake"]) // 10 通过key访问value,不存在的key会返回null
// 有size属性

Reference

https://developer.android.com/courses/android-basics-compose/course

Author

SGSG

Posted on

2025-03-24

Updated on

2025-04-18

Licensed under