【发布时间】:2017-11-18 00:38:10
【问题描述】:
我正在尝试创建一个类,它使用自己的状态来操作它所引用的外部对象的状态。外部对象可以是 A 类或 B 类,它们是相似的,但不受作者控制。因此,根据this earlier answer from @SimY4,创建了一个密封类来访问它们的公共属性。
// *** 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 添加魔法;和
- 请注意,尽管 ABTool 工具是相同的,但它们用于添加魔法的方式在 A 和 B 中略有不同,就像访问 A 和 B 的概念上通用元素的方式可能不同一样。
对此或类似的解决方法有什么想法吗?也许是我还没有想到的更实用的方法?
【问题讨论】:
标签: kotlin abstract-class inner-classes sealed data-class