如何在Kotlin中使用带有泛型的密封类

huangapple go评论57阅读模式
英文:

How to use sealed classes with generics in kotlin

问题

类型不匹配。需要:Base<Data>.() -> Unit 找到:A.() -> Unit

请告诉我正确的用法。

英文:

I can't find a solution to this problem

data class Data(val s: String)
sealed class Base&lt;T&gt;(val t: T, val f: Base&lt;T&gt;.() -&gt; Unit)
class A(data: Data, f: A.() -&gt; Unit) : Base&lt;Data&gt;(data, f)

Type mismatch.Required:Base&lt;Data&gt;.() → Unit Found: A.() → Unit

Please tell me what should be the correct usage

答案1

得分: 2

问题与密封类无关,也与泛型无关。这与以下代码中的问题相同:

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

fun fd(block: Int.() -> Unit) {
    fb(block)  // 错误: 需要: Number.() -> Unit, 找到: Int.() -> Unit
}

从上面对问题的简化可以看出,错误的原因是你不能将 Subclass.() -> Unit 块传递给期望 Base.() -> Unit 块的地方。如果这是可能的话,那么你将能够使用一个作用于 Int 的块来调用 fd,但是 fb 却将其传递给了一个 BigDecimal。因此,你需要将你的类 A 更改为:

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

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.() -&gt; Unit) {
    BigDecimal.ONE.block()
}

fun fd(block: Int.() -&gt; Unit) {
    fb(block)  // Error: required: Number.() -&gt; Unit, found: Int.() -&gt; 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.() -&gt; Unit block to something that expects a Base.() -&gt; 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&lt;Data&gt;.() -&gt; Unit) : Base&lt;Data&gt;(data, f)

huangapple
  • 本文由 发表于 2023年6月1日 16:17:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76379933.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定