带 T.() 的 Kotlin 函数签名意味着什么?

2024-04-22

这是一个标准的 Kotlin 函数(据我所知)

inline fun<T> with(t: T, body: T.() -> Unit) { t.body() }

但有人能用简单的英语写出签名的确切含义吗?它是 T 的通用函数,第一个参数为“t” T 类型,第二个是函数类型的“body”,接受 ???? 的函数并没有返回任何内容(单位)

我看到这个符号 Something.() -> Something 被频繁使用,即对于 Anko:

inline fun Activity.coordinatorLayout(init: CoordinatorLayout.() -> Unit) = ankoView({ CoordinatorLayout(it) },init)

但我认为没有在任何地方解释 .() 的含义......


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,但仅当可以从上下文推断接收者类型时它才有效。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

带 T.() 的 Kotlin 函数签名意味着什么? 的相关文章

随机推荐