T.() -> Unit
是带有接收器的扩展功能类型。
除了普通函数之外,Kotlin 还支持扩展函数。此类函数与普通函数的不同之处在于它具有接收器类型规范。这是一个通用的T.
part.
The this
扩展函数中的关键字对应于接收者对象(点之前传递的那个),因此您可以直接调用其方法(参考this
来自父范围的仍然是可能的有预选赛 https://kotlinlang.org/docs/reference/this-expressions.html).
功能with
是标准的,是的。这是当前的代码:
/**
* Calls the specified function [block] with the given [receiver] as its receiver and returns its result.
*
* For detailed usage information see the documentation for [scope functions](https://kotlinlang.org/docs/reference/scope-functions.html#with).
*/
public inline fun <T, R> with(receiver: T, block: T.() -> R): R = receiver.block()
所以它是一个通用函数T
and R
,第一个参数为“接收者”类型T
第二,f
扩展函数类型,它扩展了T
, 返回类型R
又由with
.
例如,您可以这样使用它:
val threadInfoString = with (Thread.currentThread()) {
// isDaemon() & getPriority() are called with new property syntax for getters & setters
"${getName()}[isDaemon=$isDaemon,priority=$priority]"
}
请参阅此处的扩展功能文档:
kotlinlang.org/docs/reference/lambdas.html#extension-function-expressions https://kotlinlang.org/docs/reference/lambdas.html#extension-function-expressions
kotlinlang.org/docs/reference/scope-functions.html#with https://kotlinlang.org/docs/reference/scope-functions.html#with
kotlinlang.org/docs/reference/extensions.html https://kotlinlang.org/docs/reference/extensions.html
Added:
所以唯一有效的f
是否可以为 T 定义任何 0 参数函数?
并不真地。在科特林中函数类型和扩展函数类型统一 http://blog.jetbrains.com/kotlin/2015/04/upcoming-change-function-types-reform/,以便它们可以互换使用。例如,我们可以将 String::length 传递给函数(String) -> Int
是期待。
// map() expects `(String) -> Int`
// argument has type `String.() -> Int`
strings.map(String::length)
类型如Thread.() -> String
& (Thread) -> String
从后台来看是一样的——接收者,实际上是第一个参数。
所以以下任何一个函数都适合Thread.() -> String
争论:
fun main(args: Array<String>) {
val f1 = fun Thread.(): String = name
val f2 = fun Thread.() = name
val f3: Thread.() -> String = { name }
val f4: (Thread) -> String = { it.name }
val f5 = { t: Thread -> t.name }
val f6: (Thread) -> String = Thread::getNameZ
val f7: Thread.() -> String = Thread::getNameZ
val f8 = Thread::getNameZ
}
fun Thread.getNameZ() = name
或者你可以简单地使用函数字面量 https://kotlinlang.org/docs/reference/lambdas.html#function-literal-syntax ({}
)如示例中所示threadInfoString
,但仅当可以从上下文推断接收者类型时它才有效。