和在Kotlin中运行之间的区别 [英] Difference between with and run in Kotlin

查看:130
本文介绍了和在Kotlin中运行之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Do with and run have the same functionality with only different syntax, or is there any major differences between with and run?

哪种方法合适?

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
}

推荐答案

它们只有句法上的区别,run

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类型的隐式参数,因此参数类型相同.这些功能的主体实际上也是相同的.

Since run is an extension function, it has one more implicit argument of type T, so the argument types are the same. The bodies of the functions are also effectively the same.

它们的性能也应相同,因为两者都是 inline函数:产生的字节码应仅包含内联的block正文.

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

所有功能用法上的差异都是由run是扩展名这一事实造成的.

The differences in the functions usage are all caused by the fact that run is an extension.

首先,run适用于呼叫链接:

First, run is suitable for calls chaining:

foo.run { bar }.run { baz }

第二,更重要的是,如果声明的变量类型具有具有相同签名的run函数,则将调用它而不是扩展名.并且run可以被另一个扩展名遮盖.这是>解析扩展名的方式.示例:

Second, and more important, if a declared variable type has run function with the same signature, it will be called instead of the extension. And run can be shadowed by another extension. This is how extensions are resolved. Example:

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中运行之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆