jean
01/25/2023, 8:56 AMsealed class DataTest {
data class A(val value: String): DataTest()
data class B(val value: String): DataTest()
data class C<Type>(val value: Type): DataTest()
}
fun test(dataClass: DataTest.A) = println("A: ${dataClass.value}")
fun test(dataClass: DataTest.B) = println("B: ${dataClass.value}")
fun test(dataClass: DataTest.C<*>) = println("C: ${dataClass.value}")
fun reducer(dataClass: DataTest) = test(dataClass) // compiler complains that there is no test function with parameter DataTest
@Test
fun shouldWork() {
reducer(DataTest.A("a"))
reducer(DataTest.B("b"))
reducer(DataTest.C(0))
}
Since the sealed class defines exactly the number of child for DataTest
couldn’t the compiler check that there is a test
function for each child? Instead of implementing a whole visitor patternSam
01/25/2023, 9:02 AMephemient
01/25/2023, 9:03 AMfun reducer(dataClass: DataClass) = when (dataClass) {
is A -> test(dataClass)
is B -> test(dataClass)
is C -> test(dataClass)
}
but yeah, as Sam says, the fact that the three functions have the same name is irrelevantjean
01/25/2023, 9:04 AMwhen
🤷🏻Sam
01/25/2023, 9:05 AMwhen
is kind of the whole point of a sealed type.Sam
01/25/2023, 9:06 AMjean
01/25/2023, 9:07 AMwhen
quite often, it was more of a theoretical wonderCLOVIS
01/25/2023, 9:08 AMabstract
or open
to allow it, etc)Sam
01/25/2023, 9:09 AMjean
01/25/2023, 9:10 AMwhen
statement for C with this
is C<String> -> ...
is C<Int> -> ...
CLOVIS
01/25/2023, 9:11 AMephemient
01/25/2023, 9:11 AMArray<>
, for somewhat historical Java reasons)