0

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

  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Jun 01 '23 at 10:10

1 Answers1

2

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)
k314159
  • 5,051
  • 10
  • 32