本文介绍了在Kotlin的密封课程之外进行参考?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个使用其自己的状态对持有引用的外部对象的状态进行操作的类.外部对象可以是A或B类,这是相似的,但不受作者控制.因此,根据> @ SimY4早先的答案,我们创建了一个密封的类来访问它们的公共属性. /a>.

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:

对此或类似的解决方法有何想法?也许我还没有想到一种更实用的方法?

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:

  1. ABTool声明中用inner abstract替换sealed;
  2. 也将BoxABoxB标记为inner
  1. Replace sealed with inner abstract at the ABTool declaration;
  2. Mark BoxA and BoxB as inner 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}"
}

(或者,将BoxABoxB移出ABTool的范围,而不是将AB标记为内部)

(alternatively, instead of marking AB as inner, move BoxA and BoxB out of it to the scope of ABTool)

这篇关于在Kotlin的密封课程之外进行参考?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!