Inspection: Method does not use "this"

So, in Java, there is the IntelliJ inspection “method may be static”. Anybody found an equivalent inspection for Kotlin? I mean an inspection reporting methods in classes which do not use instances of the class, or in other words, do not use the “this” reference. Such methods could/should be moved to top level or companion objects.

1 Like

Hey, sorry for the long time before answering. There is no such inspection, because it is not considered a bad thing in Kotlin to have a function in a class that could be static but isn’t.

Is that an official position? If so, why?

(ISTM a code smell to have a method on an object which doesn’t relate to that object at all — doesn’t use or modify any of its state. That applies regardless of whether that could be fixed by marking it ‘static’, or moving it to a companion object or the top level, or whatever other options the language provides.)

1 Like

I’m not in any way someone who can give an official statement on this, and I haven’t seen any discussion about this before. However I believe many people would agree with me here.

For me, there are two cases:

  • if the function is private, then it’s not important whether it uses the class or not, it’s just a utility.
  • if the function is public, then I would agree it’s a bit confusing. However, I’ve really seen anyone write such code yet.

Is this thread because you’ve seen offending code in the wild, or was it just out of curiosity?

The question popped up while migrating Java code base. What to do with the static members, put into companion, move to top level or just remove the static (in case of private)? In general, why is it different to Java? Any argument for or against this can be applied to both languages. But in Java, I believe it is consensus that the inspection is active and everyone adheres to it, but not so in Kotlin. Why? Because it has no static keyword?

My guess is because Java allows you to mark any method as static without changing the file structure.

The Kotlin creators felt mixing static and non-static members made files harder to read, so everything static was moved to the companion object in a single section. We still prefer things that are related to be close together in the file, so we prefer functions that could be static but are simply helpers for other non-static functions to stay close by than in go the companion object.