如何在Kotlin中过滤具有多个“案例”的单个列表

时间:2019-11-19 16:57:38

标签: kotlin kotlin-extension

我有一个Sealed课程,如下:-

sealed class SoundEffect {
    sealed class Acoustic : SoundEffect() {

        object Active : Acoustic()
        object Inactive : Acoustic()

        object Disable : Acoustic()
        object Enable : Acoustic()
    }

    sealed class Electronic(open val message: String) : SoundEffect() {
        data class Moog(override val message: String) : Electronic(message)
    }

    sealed class Vocal(open val dataMap: MutableMap<String, Any>) : SoundEffect() {
        data class Lieder(override val dataMap: MutableMap<String, Any> = mutableMapOf()) : Vocal(dataMap)
    }
}

以及这些值的列表:-

 private val sounds : List<Any> = listOf(
        SoundEffect.Acoustic.Active,
        SoundEffect.Acoustic.Disable,
        SoundEffect.Acoustic.Enable,
        SoundEffect.Acoustic.Inactive,
        SoundEffect.Electronic.Moog("Testing"),
        SoundEffect.Vocal.Lieder()
        )

要处理此列表,我可以这样做

  sounds.filterIsInstance<SoundEffect.Acoustic>().forEach { acoustic -> process(acoustic) }
  sounds.filterIsInstance<SoundEffect.Electronic>().forEach { electronic -> process(electronic) }
  sounds.filterIsInstance<SoundEffect.Vocal>().forEach { vocal -> process(vocal) }

我希望能够编写的代码是:-

sounds.multipleFilter {
    is SoundEffect.Acoustic -> forEach { acoustic -> process(acoustic) }
    is SoundEffect.Electronic -> forEach { electronic -> process(electronic) }
    is SoundEffect.Vocal -> forEach { vocal -> process(vocal) }
}

这种方法在科特林有可能吗?

如何指定multipleFilter函数?

1 个答案:

答案 0 :(得分:2)

正是这种语法不起作用,只有is ...中才允许使用带有when的分支。但是,为什么不只是一个forEach

sounds.forEach {
    when(it) {
        is SoundEffect.Acoustic -> process(it)
        is SoundEffect.Electronic -> process(it)
        is SoundEffect.Vocal -> process(it)
    }
}

({it将在每个分支中进行智能广播,并最终调用正确的重载)