Search code examples
kotlinconvention

Coding convention for empty functions that need to be overridden in Kotlin


Accourding to the very short Coding Conventions there is no answer for the opimal way of writing down empty functions in Kotlin.

Example:

ani.setAnimationListener(object: Animation.AnimationListener {

    override fun onAnimationRepeat(animation: Animation?) = Unit
    override fun onAnimationStart(animation: Animation?) {}

    override fun onAnimationEnd(animation: Animation?) =
        activity.runOnUiThread { loadLists() }
})

Here only one of the 3 necessary Methods of AnimationListener (Android) is used.

Which type of empty Method should be used? Single Expression (fun name() = Unit) or the traditional way used in Java (fun name() {})?

I personally like the = Unit-Way more because that seems to be meant the way of shorting functions down to one line. But {} is shorter yet older and probably more ugly.

And is there any better/shorter way for doing this code?


Solution

  • You've added link to Coding Conventions where seems like actually there is an answer to your question

    Unit

    If a function returns Unit, the return type should be omitted:

    fun foo() { // ": Unit" is omitted here

    }

    So I believe

    fun foo() {}
    

    or

    fun foo() {
    }
    

    should be the answer