How to use sealed classes with generics in kotlin

61 Views Asked by At

I can't find a solution to this problem

data class Data(val s: String)
sealed class Base<T>(val t: T, val f: Base<T>.() -> Unit)
class A(data: Data, f: A.() -> Unit) : Base<Data>(data, f)

Type mismatch.Required:Base<Data>.() → Unit Found: A.() → Unit

Please tell me what should be the correct usage

1

There are 1 best solutions below

0
On

The problem has nothing to do with sealed classes, and nothing to do with generics. It is the same problem as the following:

fun fb(block: Number.() -> Unit) {
    BigDecimal.ONE.block()
}

fun fd(block: Int.() -> Unit) {
    fb(block)  // Error: required: Number.() -> Unit, found: Int.() -> Unit
}

As you can see from the above simplification of your problem, the reason for the error is that you can't pass a Subclass.() -> Unit block to something that expects a Base.() -> Unit block. If it were possible, then you would be able to call fd with a block that acts on an Int but fb passes it a BigDecimal instead. So you need to change your class A to:

class A(data: Data, f: Base<Data>.() -> Unit) : Base<Data>(data, f)