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"