Kotlin 中密封类之外的引用? [英] Reference outside the sealed class in Kotlin?
问题描述
我正在尝试创建一个类,该类使用自己的状态来操作它持有引用的外部对象的状态.外部对象可以是A类或B类,两者相似,但不受作者控制.因此,根据 @SimY4 的早期答案,创建了一个密封类来访问它们的公共属性.
I'm trying to create a class that uses its own state to operate on the state of an external object that it holds a reference to. The external object can be of class A or B, which are similar, but not controlled by the author. So a sealed class is created to access their common attributes, per 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}"
}
现在的问题是我发现我不能以我想要的方式操作外部对象,因为密封类不能引用它的外部类成员.有没有更好的方法来完成这项工作,即使使用不同的方法(密封类除外),同时:
The problem now is that I've figured out I can't operate on the external object in the way I want, because a sealed class can't refer to its outer class members. Is there a better way to make this work, even if using a different approach (other than sealed class), while:
- 不改变外国A类或B类;
- 考虑到 A 和 B(以及实际情况中的许多其他人)是相似的,所以我正在尝试编写一个工具,使用相同的代码库来计算 A 和 B 并为 A 和 B 添加魔法;和
- 请注意,虽然 ABTool 工具是相同的,但它们用于添加魔法的方式在 A 和 B 中略有不同,就像访问 A 和 B 的概念上常见元素的方式可能不同.
对此或类似的解决方法有什么想法吗?也许我还没有想到更实用的方法?
Any thoughts on this or a similar workaround? Maybe a more functional approach that I haven't conceived yet?
推荐答案
如果 ABTool
作为一个密封类是你可以放弃的,那么这里有一个解决方案:
If ABTool
being a sealed class is something you can give up, then here's a solution:
- 在
ABTool
声明中用inner abstract
替换sealed
; - 将
BoxA
和BoxB
标记为inner
;
- Replace
sealed
withinner abstract
at theABTool
declaration; - Mark
BoxA
andBoxB
asinner
as well;
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<的范围内/code>)
(alternatively, instead of marking AB
as inner, move BoxA
and BoxB
out of it to the scope of ABTool
)
这篇关于Kotlin 中密封类之外的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!