withrun是否有相同的功能,只是语法不同,或者withrun之间有什么主要区别?

哪一种是正确的方法?

adapter.run {
    notifyDataSetChanged()
    if (activityDetails.isEmpty())
        emptyText.visibility = View.VISIBLE
    else 
       emptyText.visibility = View.GONE
}


with(adapter){
   notifyDataSetChanged()
   if (activityDetails.isEmpty())
       emptyText.visibility = View.VISIBLE
   else 
       emptyText.visibility = View.GONE
}

推荐答案

They have only syntactic difference, run is an extension function while with is not. Here are the definitions (in kotlin-sdlib:1.0.3):

public inline fun <T, R> T.run(block: T.() -> R): R = block() // equivalent to this.block()

public inline fun <T, R> with(receiver: T, block: T.() -> R): R = receiver.block()

由于run是一个扩展函数,它又有一个T类型的隐式参数,因此参数类型是相同的.这些职能机构实际上也是相同的.

Their performance should also be equivalent since both are inline functions: the resulting bytecode should only contain the inlined block body.


函数用法的差异都是由run是一个扩展这一事实造成的.

First, run is suitable for calls chaining:

foo.run { bar }.run { baz }

其次,也是更重要的是,如果声明的变量类型具有具有相同签名的run个函数,则将调用该函数,而不是调用扩展.并且run可以被另一个扩展所遮蔽.这是how extensions are resolved美元.示例:

class MyClass {
     fun <R> run(blockIgnored: MyClass.() -> R): Nothing = throw RuntimeException()
}

"abcdefg".run { println("x") } // prints "x"
MyClass().run { println("x") } // throws RuntimeException
(MyClass() as Any).run { println("x") } // prints "x"

Kotlin相关问答推荐

Fleet无法从构建文件自动重新加载更改错误'

在Kotlin 有更好的结合方式?

如何通过更改现有数据类型来执行Android房间数据库迁移?

Kotlin 复制列表中的项目以创建具有相同数据的不同对象的新列表

找不到有效的 Docker 环境

Kotlin 启动与启动(Dispatchers.Default)

如何在 Kotlin for Android 上使用setTextColor(hexaValue),

在 kotlin 中模拟伴随对象函数

AIDL 中的 Parcelize 注释:Incompatible types: Object cannot be converted to MyCustomObject

如何为 material.Slider 视图创建绑定适配器?

OnClickListener 未在 ConstraintLayout 上触发

Kotlin:内部类如何访问在外部类中声明为参数的变量?

来自类型参数的属性的自定义 getter

Kotlin Compose,在行中对齐元素

从片段(fragment)中的点击事件启动协同程序

如何让数据类在Kotlin中实现接口/扩展超类属性?

spring.config.location 在 Spring Boot 2.0.0 M6 上不起作用

如何在Kotlin中使用Handler和handleMessage?

使用 rxbinding 时我应该取消订阅吗?

Kotlin类型安全类型别名