【问题标题】:What is receiver in Kotlin? [duplicate]Kotlin 中的接收器是什么? [复制]
【发布时间】:2019-07-05 20:08:06
【问题描述】:

有人告诉我 Kotlin 中的 receiver 是什么?我查看了官方文档,但我无法理解它是什么。

你也可以告诉我Int.在下面的代码中有什么功能:

Int.(Int, Float) -> Int

【问题讨论】:

    标签: kotlin


    【解决方案1】:

    一般来说,接收者是this,当前实例。

    在 Kotlin 中,带有接收器的 lambda(这是 Int.(Int, Float) -> Int 是什么)是一种定义函数的方法,其行为类似于其接收器的方法:它们可以使用 this 引用接收器,并且可以轻松调用其他方法和接收器的属性。 (私有方法和属性除外。)

    这里是一些示例代码,你给出的 lambda 类型,其中接收器是 Int 类型。实际的接收器实例作为第一个参数传递给invoke

    val lambdaWithReceiver: Int.(Int, Float) -> Int = { firstArgument, secondArgument ->
        println("this = $this") // accessing this
        println("this.toLong() = ${toLong()}") // calling Int's methods
        println("firstArgument = $firstArgument")
        println("secondArgument = $secondArgument")
        this + 3
    }
    
    // passes 7 as the receiver, 3 and 2F as the arguments
    val result = lambdaWithReceiver.invoke(7, 3, 2F) 
    println("result = $result")
    

    上面的sn -p会打印出如下输出:

    this = 7
    this.toLong() = 7
    firstArgument = 3
    secondArgument = 2.0
    result = 10
    

    【讨论】:

    • 所以据我了解,接收器是传递的第一个参数,也可以使用它来调用。对吗?
    猜你喜欢
    • 2018-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-30
    • 1970-01-01
    • 2018-08-11
    • 1970-01-01
    相关资源
    最近更新 更多