我想问一个我有一些线索的问题,但我不想影响我将得到的答案.我有以下类层次 struct :

abstract class MyAbstractClass { 
    fun displayStuff(id: String) {
        println("My id is $id.")
    }
}

interface MyInterface {
     fun displayThis() {
        displayStuff("some-value")
      }
     fun displayStuff(id: String) // Not implemented here
}

class MyConcreteClass(): MyAbstractClass(), MyInterface {
    fun doStuff() {
        displayThis()
    }
}

fun main() {    
    val result = MyConcreteClass()
    result.doStuff()
    result.displayStuff("id")
}

这个设计有什么问题,你建议我如何解决?

推荐答案

displayStuff提取到另一个接口可能不是一个坏主意.然后MyAbstractClassMyInterface都可以从相同的接口派生.

interface DisplayStuff {
    fun displayStuff(id: String)
}

abstract class MyAbstractClass: DisplayStuff {
    override fun displayStuff(id: String) = println("My id is $id.")
}

interface MyInterface : DisplayStuff {
    fun displayThis() = displayStuff("some-value")
}

Kotlin相关问答推荐

处理合成层次 struct 中的深层按钮以切换视图

Kotlin:类型不匹配:推断的类型已运行,但应等待

如何在 Kotlin 中初始化 Short 数组?

将 SharedPreferences 中的值公开为流

Kotlin 列表扩展功能

Jetpack Compose - 单击 LazyColumn 的项目时应用程序崩溃

Picasso 回调

Spring webflux bean验证不起作用

在粘贴时将 java 转换为 kotlin

找不到 androidsdk.modules

如何将 kotlin 集合作为 varagrs 传递?

DatabaseManager_Impl 不是抽象的,不会覆盖 RoomDatabase 中的抽象方法 clearAllTables()

在调用Kotlin数据类中的超类构造函数之前访问函数

如何从kotlin中的类实例化对象

TornadoFX 中设置 PrimaryStage 或 Scene 属性的方法

用于代码生成的ANTLR工具版本4.7.1与当前运行时版本4.5.3不匹配

如何使用mockk库模拟android上下文

lateinit 的 isInitialized 属性在伴随对象中不起作用

内联 Kotlin 方法没有覆盖报告

如何在 spring-boot Web 客户端中发送请求正文?