generics - 检查对象是否是 Kotlin 中的多种类型之一
问题描述
我有以下课程:
sealed class A : BaseType
sealed class B : BaseType
sealed class C : BaseType
...
如果我有一个processObject
看起来像这样的方法:
fun processObject(obj: BaseType): Int {
return when(obj) {
is A -> 1
is B -> 1
else -> 0
}
}
我注意到我现在在重复自己,所以我可能会将该方法更改为如下所示:
fun processObject(obj: BaseType): Int {
return when(obj) {
is A, is B -> 1
else -> 0
}
}
然而,当班级数量从 3-4 到 40+ 时,这(在我看来)看起来非常难看。我正在考虑按照下面的伪代码做一些事情:
// store all the possible types in a list
val typesThatShouldReturn1 = listOf<BaseType>(
// TODO: figure out how to store types in a list without instantiating
)
fun processObject(obj: BaseType): Int {
if (typesThatShouldReturn1.any { obj is it }) {
return 1
}
return 0
}
这在 kotlin 中是否可行?
回复:一些评论。
为什么我不使用标记界面?因为此processEvent
功能将在许多不同的上下文中实现,并且为每个上下文引入标记接口并不是一个好的解决方案。此外,这些baseType
类是 CQRS 系统的一部分,理想情况下,我们的写入逻辑不应该与我们的读取逻辑有关。这是标记界面对我来说不可行的最大原因。
为什么不BaseType
实现这个逻辑?请参阅上面关于processEvents
在不同上下文中以不同方式实施的评论。此外,基本类型没有读取逻辑作为关注点,这就是它永远不应该实现它的原因。
listOf(A::class, B::class, C::class, ...)
看起来比 更好吗is A, is B, is C, ...
?它看起来或多或少相同。有效点。这个更个人喜好,因为我不介意private val typesThatShouldReturn1
。
解决方案
当然,你可以写这样的东西
val typesThatShouldReturn1 = listOf(
A::class
)
fun processObject(obj: BaseType): Int {
if (typesThatShouldReturn1.any { it.isInstance(obj) }) {
return 1
}
return 0
}
推荐阅读
- android - Firebase 短动态链接 - 等待多个短链接完成
- firebase - Flutter 从 firebase 获取特定字段并将其分配给列表
- c# - C# 字符串插值和条件运算符
- python-3.x - CentOS 使用 Python 作为基础镜像
- sql - Redshift:根据另一个表中的日期范围从销售表中获取数据
- html - 真的很长的桌子从一个div出来。如何隐藏溢出的表格而不丢失其中的粘性元素?
- windows-terminal - Windows 终端与 Ubuntu.exe
- c++ - 函数模板重载解析,依赖和非依赖参数
- solr - 是否可以使用 reRank 查询来解决 Solr 查询?
- image-processing - 用于组合多个图像的代码的 Python 并行化