英文:
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<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
得分: 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.() -> 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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论