科特林强制重写一个函数

我正在创建一个基类。
我有一些代码 开始()
还有一个bar()需要被inheritanceFoo的类所超越

start()调用bar()

我的例子(foo.kt):

open class Foo { fun start() { bar() //... } fun bar() { TODO("implement me in deriving class") } } 

我不喜欢bar()抛出exception,我不喜欢把bar()留给空白的body

有什么我忘了这是在Kotlin 更好的选择

你可以使你的方法(以及你的课)变得abstract

 abstract class Foo { fun start() { bar() //... } abstract bar() } 

这将强制任何从Fooinheritance的非抽象类实现bar方法,并且阻止任何人直接创建基类Foo类的实例。

您可以更改在Android Studio / Intellij中生成的默认代码:

 File -> Settings Then look for Editor -> File and Code Templates Code -> New Kotlin Function Body 

TODO("not implemented")替换为// TODO: not implemented