我正在尝试创建一个类,它使用自己的状态来操作它所引用的外部对象的状态。外部对象可以是A类或B类,它们类似,但不受作者控制。因此,根据this earlier answer from @SimY4创建了一个密封类来访问它们的公共(public)属性。 .
// *** DOES NOT COMPILE ***
class A { // foreign class whose structure is not modifiable
val prop get()= "some string made the Class-A way"
}
class B { // foreign class whose structure is not modifiable
val prop get()= "some string made the Class-B way"
}
data class ABTool (val obj:AB, val i:Int, val j:Int) {
// class that manipulates i and j and uses them to do
// things with AB's "common" attributes through the sealed class AB
sealed class AB { // substitute for a common interface
abstract val prop: String
abstract val addmagic: String
data class BoxA(val o:A) : AB() {
override val prop get()= o.prop
override val addmagic get() = prop + this@???.magic // HOW TO REFERENCE?
}
data class BoxB(val o:B) : AB() {
override val prop get()= o.prop
override val addmagic get() = this@???.magic + prop // HOW TO REFERENCE?
}
}
val magic get()= "magic: ${i*j}"
}
现在的问题是我发现我无法按照我想要的方式操作外部对象,因为密封类无法引用其外部类成员。有没有更好的方法来完成这项工作,即使使用不同的方法(密封类除外),同时:
- 不改变外国A级或B级;
- 考虑到 A 和 B(以及实际情况中的许多其他情况)是相似的,因此我尝试编写一个工具,使用相同的代码库来计算 A 和 B 并为 A 和 B 添加魔力;和
- 请注意,尽管 ABTool 工具相同,但在 A 和 B 中应用它们来添加魔法的方式略有不同,就像访问 A 和 B 的概念上公共(public)元素的方式可能不同一样。
对此或类似的解决方法有什么想法吗?也许是我还没有想到的更实用的方法?
最佳答案
如果您可以放弃 ABTool
作为密封类,那么这里有一个解决方案:
- 将
ABTool
声明中的sealed
替换为inner Abstract
; - 将
BoxA
和BoxB
也标记为inner
;
data class ABTool(val obj: AB, val i: Int, val j: Int) {
inner abstract class AB {
abstract val prop: String
abstract val addmagic: String
inner class BoxA(val o: A) : AB() {
override val prop get() = o.prop
override val addmagic get() = prop + magic
}
inner class BoxB(val o: B) : AB() {
override val prop get() = o.prop
override val addmagic get() = magic + prop
}
}
val magic get() = "magic: ${i * j}"
}
(或者,不要将 AB
标记为内部,而是将 BoxA
和 BoxB
移出它到 ABTool< 的范围
)
关于kotlin - 在 Kotlin 密封类之外引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47361279/