
[英]kotlin annotation processing: check if given TypeElement is from kotlin-class
[英]Why is this Kotlin-class an abstract class?
我得到了有人写的这段代码:
abstract class ListItem {
companion object {
private var id = 0
fun getUUID() = id++
}
}
fun getItem(uuid: Int): ListItem? {
for (dessert in Dessert.getAllDesserts())
if (dessert.id == uuid)
return dessert
for (fruit in Fruit.getAllFruits())
if (fruit.id == uuid)
return fruit
return null
}
子类示例:
data class Fruit(
val id: Int,
val resId: Int,
val name: String,
val origin: String,
val desc: String
): ListItem() {
companion object {
private val fruits = listOf(
Fruit(getUUID(), R.drawable.f1_durian, "Durian", "Indonesia", "Often dubbed the king of fruit, durian is an unusual tropical fruit that grows throughout Southeast Asia. A large spiky outer shell reveals a creamy, almost custard-like flesh, which, besides boasting a mildly sweet flavor, is notorious for being incredibly rank-smelling."),
我不明白为什么 ListItem 是一个抽象的 class。没有未实现的方法。
使 ListItem 成为抽象 class 的动机是什么?
有人有想法吗?
就像mr mcwolf
给出的很好的例子一样,这里的“问题”是一个概念性的问题:虽然您可以允许实例化ListItem
,但它的目的是什么? 如果我们谈论食品,它没有“物理”意义。
但是,请务必注意, interface
是一种更好的方法,因为在您提供的示例中使用 inheritance 没有实际好处,甚至可能会产生误导。
如果,在这种情况下, ListItem
变成了一个“标记” interface
,它就达到了不能直接实例化的目的,并有助于泛型类型化(例如,如果以后使用),同时不会破坏其他一些所需的行为(例如,将两者都放在Food
层次结构下的Fruit
和Dessert
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.