Hello, I'm modeling the different types of audio f...
# codereview
l
Hello, I'm modeling the different types of audio focus as a Kotlin type hierarchy, and I'm unsure about picking
sealed interface
or
sealed class
. What would you pick? Any reason beyond personal preference? 1️⃣ Here's with `interface`:
Copy code
sealed interface AudioFocus {
    object Gain : AudioFocus
    sealed interface Loss : AudioFocus {
        companion object : Loss
        sealed interface Transient : Loss {
            companion object : Transient
            object CanDuck : Transient
        }
    }
}
2️⃣ Here's with `class`:
Copy code
sealed class AudioFocus {
    object Gain : AudioFocus()
    sealed class Loss : AudioFocus() {
        companion object : Loss()
        sealed class Transient : Loss() {
            companion object : Transient()
            object CanDuck : Transient()
        }
    }
}
1️⃣ 3
2️⃣ 2
j
If an interface can be used, I would use it, if you need local variables with backing fields, I would use a class
👍🏼 1
1
e
sealed interfaces don't protect you from instantiation in Java, so at least until support for JEP 360 lands, I'd use sealed classes except when interfaces are required (multiple hierarchies, enums)
on a different note, while the use of
companion object
here will look nice with
AudioFocus.Loss
being usable as a value, I think it's awkward that its type is actually
AudioFocus.Loss.Companion
.
I don't really have a better option though
although because AUDIOFOCUS_GAIN_TRANSIENT AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE also exist, I think this hierarchy isn't really so clean…
z
1 if you’re only targeting kotlin consumers, 2 if you are worried about java consumers
e
something like this, with a DAG-like set of hierarchies instead of a single tree-like hierarchy, is only doable with
interface
l
Thanks for sharing your thoughts! I settled with
sealed interface
(Java compatibility isn't a concern in my case). Here's a full gist that includes a suspend-first API to work with AudioFocus on all Android versions: https://gist.github.com/LouisCAD/4ca4bd6cb85e3d8b2509492d67b282f7