首页 > 解决方案 > 检查对象是否是 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

标签: genericskotlin

解决方案


当然,你可以写这样的东西

val typesThatShouldReturn1 = listOf(
  A::class
)

fun processObject(obj: BaseType): Int {
  if (typesThatShouldReturn1.any { it.isInstance(obj) }) {
    return 1
  }
  return 0
}

推荐阅读