简体   繁体   中英

How to filter a single list with multiple “cases” in Kotlin

I have a Sealed class as follows:-

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)
    }
}

and a list of these values:-

 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()
        )

To process this list I can do this

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

What I would like to be able to code is this:-

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

is this approach possible in Kotlin?

How could I specify the multipleFilter function?

Exactly this syntax won't work, branches with is... are only allowed in when . But why not just a single forEach ?

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

( it will be smart-cast in each branch and end up calling the correct overload)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM