Kotlin一些迷惑的语法

Kotlin 复制代码
 protected fun sendUiState(copy: S.() -> S) {
        _uiStateFlow.update { copy(uiStateFlow.value) }
    }

疑惑点:为什么传入的方法是无参数的,但是为什么调用的时候传入值?

这个 copy 函数的签名虽然看起来没有参数 ,但它的本质是一个 带接收者的函数 ,它会在一个 S 类型的对象上调用。所以:

copy(uiStateFlow.value)

不是把 uiStateFlow.value 当作参数传入 ,而是把它作为接收者对象调用这个 lambda

和如何写法是一样的,因为编译成java的时候,参数中是带有当前的对象的

Kotlin 复制代码
  protected fun sendUiState(copy: S.() -> S) {
        _uiStateFlow.update { uiStateFlow.value.copy() }
    }

Iterable

在 Kotlin 中,Iterable 是一个接口,表示可以被迭代的一组元素 。它是 Kotlin 集合体系的基础接口之一,类似于 Java 中的 Iterable<T>

✅ 基本定义:

Kotlin 复制代码
public interface Iterable<out T> {
    operator fun iterator(): Iterator<T>
}
  • T 是集合中元素的类型。

  • Iterable 的本质是:只要你能 for 遍历它,它就是 Iterable。

✅ 典型实现:

以下都是 Iterable 的子类型:

  • List

  • Set

  • Map.keys / Map.values

  • 自定义只要实现了 iterator() 方法的类

✅ 常用操作(来自扩展函数)

Kotlin 给 Iterable<T> 添加了大量实用的扩展函数,比如:

操作函数 功能
forEach {} 遍历每个元素
map {} 转换为另一个集合
filter {} 条件筛选
first {} / find {} 查找匹配项
any {} / all {} 判断是否满足条件
groupBy {} 分组
sortedBy {} 排序
toList() / toSet() 转换为 List 或 Set
复制代码
val list = (0 until  3).map {  "转成string" + it }

map的一些用法,(0 until 3)也是一个迭代器

相关推荐
Coffeeee6 小时前
面试被问到Compose的副作用不会,只怪我没好好学
android·kotlin·android jetpack
wuwu_q1 天前
用通俗易懂方式,详细讲讲 Kotlin Flow 中的 map 操作符
android·开发语言·kotlin
会跑的兔子2 天前
Android 16 Kotlin协程 第一部分
android·开发语言·kotlin
来来走走2 天前
Android开发(Kotlin) 高阶函数、内联函数
android·开发语言·kotlin
来来走走3 天前
Android开发(Kotlin) 扩展函数和运算符重载
android·开发语言·kotlin
wuwu_q3 天前
用通俗易懂 + Android 开发实战的方式,详细讲解 Kotlin Flow 中的 retryWhen 操作符
android·开发语言·kotlin
li-jia-wei3 天前
我在造一个编程语言,叫 Free
kotlin
Android-Flutter3 天前
kotlin - 显示HDR图(heic格式),使用GainMap算法,速度从5秒提升到0.6秒
android·kotlin
雨白3 天前
协程进阶:协作、互斥与共享状态管理
android·kotlin
studyForMokey4 天前
【Kotlin内联函数】
android·开发语言·kotlin