BVG
05/06/2022, 2:14 PMsealed interface SealedOf<Type>
object SealedOfString1 : SealedOf<String>
object SealedOfString2 : SealedOf<String>
object SealedOfInt1 : SealedOf<Int>
object SealedOfInt2 : SealedOf<Int>
fun theIssue() {
// Note that variable restricts the values only to SealedOf<String>
var subject : SealedOf<String> = SealedOfString1
// This is the only way to have exhaustive when statement - and it produces a compilation error:
// Incompatible types: SealedOfInt1 and SealedOf<String>
when (subject) {
SealedOfString1 -> TODO()
SealedOfString2 -> TODO()
SealedOfInt1 -> TODO()
SealedOfInt2 -> TODO()
}
// This produces warning or error:
// Non exhaustive 'when' statements on sealed class/interface will be prohibited in 1.7,
// add 'SealedOfInt1', 'SealedOfInt2' branches or 'else' branch instead
when (subject) {
SealedOfString1 -> TODO()
SealedOfString2 -> TODO()
}
}
It'd be nice for compiler to understand that SealedOf<Int>
types cannot be assigned to the variable, and therefore no SealedOfInt1, SealedOfInt2
branches are needed. Writing else
branch resolves the compilation error, but that is not why sealed types are used 🙂hfhbd
05/06/2022, 2:38 PMsealed interface SealedOf<Type>
sealed interface SealedOfString: SealedOf<String>
object SealedOfString1 : SealedOfString
object SealedOfString2 : SealedOfString
sealed interface SealedOfInt: SealedOf<Int>
object SealedOfInt1 : SealedOfInt
object SealedOfInt2 : SealedOfInt
fun theIssue() {
// Note that variable restricts the values only to SealedOf<String>
var subject : SealedOfString = SealedOfString1
// This is the only way to have exhaustive when statement - and it produces a compilation error:
// Incompatible types: SealedOfInt1 and SealedOf<String>
when (subject) {
SealedOfString1 -> TODO()
SealedOfString2 -> TODO()
}
BVG
05/06/2022, 2:46 PMrnett
05/06/2022, 3:22 PMBVG
05/06/2022, 4:24 PMBVG
05/09/2022, 12:06 PM