和在Kotlin中运行之间的区别 [英] Difference between with and run in Kotlin
问题描述
with
和run
是否具有相同的功能,只是语法不同,或者with
和run
之间是否有主要区别?
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
}
推荐答案
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屋!