【发布时间】:2020-01-15 06:05:01
【问题描述】:
我有以下 Java 代码,我想将其转换为 Kotlin:
class RideHistoryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
class HistoryItemHolder extends RecyclerView.ViewHolder {
private static final int TYPE_IN_PROGRESS = 1
private static final int TYPE_CANCELLED = 2
private static final int TYPE_FINISHED = 3
// class methods and properties are written
}
}
我想出了以下代码:
class RideHistoryAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private inner class HistoryItemHolder(view: View)
: RecyclerView.ViewHolder(view) {
private companion object {
private const val TYPE_IN_PROGRESS = 1
private const val TYPE_CANCELLED = 2
private const val TYPE_FINISHED = 3
// class methods and properties are written
}
}
}
Android Studio 在companion object 行的“对象”下方显示红色波浪线,表示:
此处不允许伴随对象
注意:我知道我可以将其转换为非内部类,但我更愿意保留它。我还检查了我也不能在内部类中定义接口。
【问题讨论】:
-
您有什么特别的理由要使用内部类吗?
-
@NatigBabayev 避免显式传递适配器的属性(内部类减少了额外的调用和值的维护)。
-
那为什么不把伴生对象移到父类呢?
-
@NatigBabayev 是的,我可以这样做,但由于它与 HistoryItemHolder(内部类)而不是 RecyclerVIew(父级)有关,因此设计上是错误的。