Empty Method: Unit or Empty Block

There is no information about this in kotlin code style guide

If I have interface

interface SomeInterface {
    fun someMethod()
}

And I want do nothing, how i should do it?

class UnitSome: SomeInterface {
    override fun someMethod() = Unit
}

Or

class CommentSome: SomeInterface {
    override fun someMethod() {
        // Do nothing
    }
}

Or

class CommentSome: SomeInterface {
    override fun someMethod() { /* Do Nothing */ }
}

This is probably off topic.
I think all three options are fine but I must say the comment here is the list important part.

Clearly the method does nothing–adding a doc-comment or comment for why should always be done.

Comments that say what the code is doing is a semi codesmell that your code isn’t clear. After all, your code should read just as clearly as a comment describing what it does.

Comments explaining why code does what it does has real value.


I usually go with option #2 and have a comment inside explaining why. I probably do that because of Java though.
Option #1 seems nice as well. We lose the comment on the inside but I could understand an argument that all of those comments should be doc comments.
Option #3 I like the least but I’m sure I’ve used it before.

1 Like

Well said!!

Comments are there to tell you things that aren’t already clear from the code.⠀Things like why it’s done this way (especially if you’d normally expect it to be done differently), or any non-obvious interactions with other parts of the system.⠀And of course function/method comments should be written from the point of view of the caller, explaining what the function does, why and when you’d want to call it, what parameters it takes, what exceptions it might throw and why, what value it returns, and how it relates to any alternatives.

So in this case, it might be good to comment why the method has no implementation, when the interface it’s implementing clearly expects some functionality to go there.⠀For example:

// No implementation, because this class doesn't have any flurgles that need zorping.

(Hmmm, the code formatter on this site clearly doesn’t recognise // as a comment marker…)

If there’s nothing useful you could say there, then there’s probably no need for a comment; an empty block is already pretty clear.

Also, I think the = Unit version might be a little harder to follow than the others, especially for those less experienced in the language, as it’s so different from the normal block bodies.⠀(And even if you’re used to expression bodies, it’s pretty rare to need to refer to the Unit value explicitly.)

3 Likes

Regarding formatting // as comment, try specifying language when defining code block, e.g.:

```
// this class
```

will render:

// this class

but

```kotlin
// this class
```

will render:

// this class

It’s a bit off topic, but maybe it would be helpful for other users of the forum.