我正在使用一种返回不同类型对象的方法,并且我正在使用Any类型来实现这一目标。
方法如下:
override fun presentNativeItem(dcsItem: DCSItem): Any {
var type = dcsItem?.type?.toUpperCase()
return when (type) {
DSCType.NAVMENU.name -> buildNavMenu(dcsItem)
DSCType.NAVLINK.name -> buildNavLink(dcsItem)
DSCType.IMAGE.name -> buildImage(dcsItem)
else -> throw IllegalStateException("Unknown Type ${dcsItem?.type} of NavItem")
}
}
类的模型就像:
abstract class NavItem {
abstract val attributes: String
abstract val text: String
abstract val hasChildren: Boolean
abstract val childrenIds: List<Int>?
abstract val items: List<NavItem>?
abstract val hasImages: Boolean
abstract val image: String?
}
data class NavMenu(override val items: List<NavItem>?,
override var image: String?,
override val attributes: String,
override val text: String,
override val hasChildren: Boolean,
override val childrenIds: List<Int>?,
override val hasImages: Boolean) : NavItem()
data class NavLink(override val items: List<NavItem>?,
val shortText: String?,
override var image: String?,
override val attributes: String,
override val text: String,
override val hasChildren: Boolean,
override val childrenIds: List<Int>?,
override val hasImages: Boolean) : NavItem()
最后我以另一种方式使用此方法:
override fun getNavItemById(dCSServiceContext: DCSServiceContext): Single<Any> {
return scribeProvider.getNavItemById(dCSServiceContext).map { navItem ->
scribePresenter.presentNativeItem(navItem)
}
}
我已经阅读了有关密封类的信息,但是您必须在密封类内部使用构造函数创建类,但是我有一个无法修改的模型,因为该模型已在多个地方使用。
有什么想法吗?
谢谢!
答案 0 :(得分:1)
将不同的返回类型包装在密封的类层次结构中,并从函数中返回NativeItem
:
sealed class NativeItem
class NavMenuItem(val menu: NavMenu) : NativeItem()
class NavLinkItem(val link: NavLink) : NativeItem()
class ImageItem(val image: Image) : NativeItem()