当我们有扩展功能时,Kotlin中带接收器的Lambda的用途是什么?

Two functions below do the same things, however first one is more readable and short:

fun main(args: Array<String>) {
    println("123".represents(123))
    println(123.represents("123"))
}

fun String.represents(another: Int) = toIntOrNull() == another

val represents: Int.(String) -> Boolean = {this == it.toIntOrNull()}

推荐答案

带接收器的lambda基本上与扩展函数完全相同,它们只能存储在属性中,并传递给函数.这个问题本质上等同于"当我们有功能时,lambdas的用途是什么?"答案也大同小异-它允许您在代码中的任何位置快速创建匿名扩展函数.

There are many good use cases for this (see DSLs in particular), but I'll give one simple example here.

For instance, let's say you have a function like this:

fun buildString(actions: StringBuilder.() -> Unit): String {
    val builder = StringBuilder()
    builder.actions()
    return builder.toString()
}

调用此函数如下所示:

val str = buildString {
    append("Hello")
    append(" ")
    append("world")
}

这项语言功能提供了几个有趣的功能:

  • Inside the lambda you pass to buildString, you're in a new scope and as such have new methods and properties available for use. In this specific case, you can use methods on the StringBuilder type without having to call them on any instance.
  • The actual StringBuilder instance these function calls are going to be made on is not managed by you - it's up to the internal implementation of the function to create one and call your extension function on it.
  • Consequently, it would also be possible for this function to do much more than just call the lambda you passed to it once on one StringBuilder - it could call it multiple times, on various StringBuilder instances, store it for later use, etc.

Kotlin相关问答推荐

如何在Jetpack Compose中的列中渲染图像

测试Compose Multiplatform UI时,为另一个文件设置ComposeRule()

用普通Kotlin理解Gradle的Kotlin DSL'""

在Kotlin 有更好的结合方式?

在Jetpack Compose中创建波浪式文本动画:顺序中断问题

无法访问类kotlin.coroutines.CoroutineContext';.判断模块类路径中是否存在丢失或冲突的依赖项

可以从背景图像中点击图标吗?

用于将 0.5 变为 0 的 round() 函数的模拟

有没有什么方法或算法可以在没有存储的情况下生成唯一的随机数?

Kotlin:调用 CoroutineScope.launch 与在协程内启动之间的区别

按钮无法在 Android Studio 上打开新活动

在 Compose 中使用 Text() 时如何获取文本的大小?

测试协程和线程之间的差异,我在kotlin中使用线程时无法得到OOM错误

Kotlin:查找集合中最常见的元素

如何在 kotlin 中通过反射设置委托属性值?

什么是 .kotlin_builtins 文件,我可以从我的 uberjars 中省略它们吗?

如何在 android jetpack compose 中相互重叠列表项?

runOnUiThread 没有调用

Kotlin 中内部可见性修饰符的范围

Android room DAO 接口不适用于继承