Reference outside the sealed class in Kotlin?

懵懂的女人 提交于 2019-12-02 01:17:35

If ABTool being a sealed class is something you can give up, then here's a solution:

  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}"
}

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

An alternative would be to add an ABTool field to AB:

sealed class AB(val tool: ABTool) {
  abstract val prop: String
  abstract val addmagic: String
  data class BoxA(val o:A, tool: ABTool) : AB(tool) {
    override val prop get()= o.prop
    override val addmagic get() = prop + tool.magic
  }
  data class BoxB(val o:B, tool: ABTool) : AB(tool) {
    override val prop get()= o.prop
    override val addmagic get() = tool.magic + prop
  }
}

and pass this when creating it from ABTool. That's just what inner really does, after all.

In this specific case the field happens to be unused in AB itself and so you can remove it from there and make it val in BoxA and BoxB.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!