识别Kotlin中的关系

s8vozzvw  于 2022-12-13  发布在  Kotlin
关注(0)|答案(1)|浏览(119)

嵌套类是在Kotlin中建模标识关系的好方法吗?
要求:

  • 一个问题不能没有一个系列
  • 撤销不可能没有问题
  • 一个肯定不能没有撤销

看起来相当冗长:

class Have {
    inner class Serno(val value: String) {
        override fun toString(): String = "serno: $value"
        fun nothing () = this@Have
        inner class Issue(val value: String) {
            override fun toString(): String = "issue: $value (${serno()})"
            fun serno () = this@Serno
            inner class Revocation(val value: String) {
                override fun toString(): String = "revocation: $value (${issue()})"
                fun issue () = this@Issue
                inner class Affirmation(val value: String) {
                    override fun toString(): String = "affirmation: $value (${revocation()})"
                    fun revocation () = this@Revocation
                }
            }
        }
    }
}

val serno: Have.Serno = Have().Serno("123")
val issue: Have.Serno.Issue = serno.Issue("SUP-1")
val revocation: Have.Serno.Issue.Revocation = issue.Revocation("2020")
val affirmation: Have.Serno.Issue.Revocation.Affirmation = revocation.Affirmation("2022")

println(serno)
println(issue)
println(revocation)
println(affirmation)

println(serno == affirmation.revocation().issue().serno())

有没有更简单的方法来实现同样的目标?

zkure5ic

zkure5ic1#

这通常可以通过简单的非空属性来实现:

class Serno(val value: String) {
    override fun toString(): String = "serno: $value"
}

class Issue(val value: String, val serno: Serno) {
    override fun toString(): String = "issue: $value ($serno)"
}

class Revocation(val value: String, val issue: Issue) {
    override fun toString(): String = "revocation: $value ($issue)"
}

class Affirmation(val value: String, val revocation: Revocation) {
    override fun toString(): String = "affirmation: $value ($revocation)"
}

val serno = Serno("123")
val issue = Issue("SUP-1", serno)
val revocation = Revocation("2020", issue)
val affirmation = Affirmation("2022", revocation)

如果对toString不严格,甚至可以使用内置的toString数据类,进一步简化:

data class Serno(val value: String)

data class Issue(val value: String, val serno: Serno)

data class Revocation(val value: String, val issue: Issue)

data class Affirmation(val value: String, val revocation: Revocation)

相关问题