【问题标题】:Kotlin syntax: Difference between using the class name instead of the companion object nameKotlin 语法:使用类名而不是伴随对象名的区别
【发布时间】:2018-11-06 04:22:43
【问题描述】:

看看这段代码,它模仿了featuresKtor 应用程序中的安装方式。

fun main(args: Array<String>) {
    val app = App()
    app.installFeature(Authentication)
}

interface AppFeature {
    fun install()
}

class Authentication {

    companion object Feature : AppFeature {
        override fun install() = println("Authentication Installed")
    }
}

class App {

    fun installFeature(appFeature: AppFeature) {
        println("Installing appFeature `${appFeature::class.simpleName}`")
        appFeature.install()
    }
}

上面的 sn-p 对我来说没有意义的是这一行 app.installFeature(Authentication)

谁能向我解释为什么使用class 名称而不是companion object 名称就像app.installFeature(Authentication.Feature) 更明显的方式一样工作

【问题讨论】:

    标签: kotlin ktor


    【解决方案1】:

    documentation中提到的:

    可以通过简单地使用类名作为限定符来调用伴生对象的成员

    同样,您可以直接将Authentication 用作AppFeature

    【讨论】:

      猜你喜欢
      • 2021-11-23
      • 2017-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多