首页 > 解决方案 > Kotlin 中的每个类都扩展任何类吗

问题描述

我正在编写一个扩展函数RecyclerView来设置LayoutManagerAdapter设置RecyclerView。该函数应该接受任何扩展自的适配器类,RecyclerView.Adapter<Any>就像我们在 Java 中使用的一样。我们RecyclerView.Adapter<?>如何在 Kotlin 中实现这一点?

internal fun <T : RecyclerView.Adapter<Any>> RecyclerView.initAndSetAdapter(context: Context, adapter: T) {
    this.layoutManager = LinearLayoutManager(context)
    this.setHasFixedSize(true)
    this.adapter = adapter
}

由于类型无效,对此方法的函数调用未编译。但如果我更改Any为,*则它可以正常工作。

internal fun <T : RecyclerView.Adapter<*>> RecyclerView.initAndSetAdapter(context: Context, adapter: T) {
    this.layoutManager = LinearLayoutManager(context)
    this.setHasFixedSize(true)
    this.adapter = adapter
}

为什么方法调用不与Any类一起编译?Kotlin 中的每个类都Any像 JavaObject类一样扩展类吗?

标签: javaandroidkotlinandroid-recyclerview

解决方案


根据文档: https ://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-any/index.html

Every Kotlin class has Any as a superclass.

话虽如此 - 适配器需要的类需要从 ViewHolder 扩展。


推荐阅读