Kotlin 语法:使用 class 名称而不是伴随对象名称的区别

Kotlin syntax: Difference between using the class name instead of the companion object name

查看模仿features are installed in Ktor应用程序的代码。

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()
    }
}

上面的代码片段对我来说没有意义的是这一行 app.installFeature(Authentication)

任何人都可以向我解释为什么使用 class 名称而不是 companion object 名称就像更明显的方式 app.installFeature(Authentication.Feature)

documentation所述:

Members of the companion object can be called by using simply the class name as the qualifier

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