Kotlin中的Typealias和扩展功能

时间:2019-02-15 12:22:27

标签: kotlin kotlin-extension

当我是Kotlin新手时,我需要一些帮助来理解以下代码。这是我在网上找到的科特林帖子

typealias genericContext<T> = Demo<T>.() -> Unit
class Demo<T> {
    infix fun doThis(block: genericContext<T>) = block()
    fun say(obj: T) = println(obj.toString())
}

fun main(args: Array<String>)
{
    val demo = Demo<String>()

    demo doThis { say("generic alias") }
}

所以我了解到,由于有了infix,我们可以跳过通常的方法调用语法,即demo.doThis并执行demo doThis
但我不理解以下内容:
typealias genericContext<T> = Demo<T>.() -> Unit
这似乎将字符串genericContext<T>与看起来像lambda的东西相关联,但是我没有得到.()部分。那用功能Demo扩展了()吗?我对这是如何工作感到困惑。有人可以照亮吗?

1 个答案:

答案 0 :(得分:4)

typealias genericContext<T> = Demo<T>.() -> Unit是类型别名。它只是在右侧给类型重新命名。这意味着doThisDemo的声明与此等效:

infix fun doThis(block: Demo<T>.() -> Unit) = block()

现在输入Demo<T>.() -> Unit类型: 这是一种功能类型。此类型的函数将Demo作为接收方参数,并返回Unit。因此,它是在Demo类中定义或在Demo类中扩展的所有函数的类型。

当您提供这种类型的lambda时(例如,当您调用doThis函数时),那么this将指向lambda中的Demo对象。例如:

someDemo.doThis {
    /* "this" is an object of type `Demo`.
     * In this case it's actually "someDemo", because the implementation of "doThis" 
     * calls "block" on the implicit "this".
     */
    this.say("Hey!")
}
相关问题