var count by remember { mutableStateOf(0) }
Button(onClick = { count++ }) {
Text("Count: $count")
}
带 key 的 remember
kotlin复制代码
var name by remember { mutableStateOf("tom") }
val content = remember(name) {
"Hello, $name!"
}
Button(onClick = {
if (name == "tom") {
name = "jerry"
} else if (name == "jerry") {
name = "tom"
}
}, content = {
Text(content)
})
kotlin复制代码
var name by remember { mutableStateOf("tom") }
var age by remember { mutableStateOf(18) }
val content = remember(name, age) {
"Hello, $name! You are $age years old."
}
Button(onClick = {
name = "jerry"
age = 20
}, content = {
Text(content)
})
3、数据类型状态
基础类型状态
kotlin复制代码
var inputText by remember { mutableStateOf("") }
Column {
TextField(
value = inputText,
onValueChange = { inputText = it },
label = { Text(text = "请输入内容") }
)
Text("你输入的内容:$inputText")
}
kotlin复制代码
var isChecked by remember { mutableStateOf(false) }
Column {
Switch(
checked = isChecked,
onCheckedChange = { isChecked = it }
)
Text("开关状态:${if (isChecked) "开启" else "关闭"}")
}
fun test(operation: () -> Unit): Unit {
println("测试开始")
operation()
println("测试结束")
}
test {
println("测试操作...")
}
复制代码
# 输出结果
测试开始
测试操作...
测试结束
kotlin复制代码
fun custom_compute(operation: (Int, Int) -> Int): Unit {
println("计算开始")
val result = operation(10, 20)
println("计算结果:$result")
}
custom_compute { a, b ->
a + b
}
复制代码
# 输出结果
计算开始
计算结果:30
传递函数类型参数
使用 Lambda 表达式
kotlin复制代码
fun custom_compute(operation: (Int, Int) -> Int): Unit {
println("计算开始")
val result = operation(10, 20)
println("计算结果:$result")
}
custom_compute { a, b ->
a + b
}
复制代码
# 输出结果
计算开始
计算结果:30
使用函数引用
kotlin复制代码
fun custom_compute(operation: (Int, Int) -> Int): Unit {
println("计算开始")
val result = operation(10, 20)
println("计算结果:$result")
}
fun custom_compute_operation(a: Int, b: Int): Int {
return a * b
}
custom_compute(::custom_compute_operation)
复制代码
# 输出结果
计算开始
计算结果:200
使用匿名函数
kotlin复制代码
fun custom_compute(operation: (Int, Int) -> Int): Unit {
println("计算开始")
val result = operation(10, 20)
println("计算结果:$result")
}
custom_compute(fun(a: Int, b: Int): Int {
return a - b
})