Object or top level property name warning

I get a warning when I start a private property name with an underscore in an Object.

object Foo {
private val _bar = 3 // Warning

Anybody know what the reasoning is?

1 Like

Same as for any other naming conventions warning: the Kotlin style guide tells you not to use such names.

But as far as I know the convention when you have something like this is to use an underscore at the start of the name.

private val _list = mutableListOf(1, 2, 3)
val list: List<Int>
    get() = _list

How would one name the private backing field here?


Came here for this exact reason. I guess I can live with not doing this, but would like to understand why this is discouraged for objects but not for classes. @yole

1 Like

If you look at the latest version of the Kotlin Coding Conventions and the property naming rules in particular, then firstly it says that you should use an underscore prefix to distinguish a private backing field from the corresponding public property, which answers the question which @Wasabi375 raised two months back.

Secondly, this is the only situation I can find where underscore prefixes should be used.

Thirdly, the only area I can find where classes differ from objects is that val properties of the latter which have no custom getter and that hold deeply immutable data (and which therefore to all intents and purposes are constants) should use upper case underscore separated names.

So taking that literally, @nbilyk’s example should be written:

object Foo {
    private val BAR = 3  // upper case as effectively a constant

As to the general point of why leading underscores tend to be frowned upon not just by Kotlin but by many other languages, I think the answer is that (1) they’re best reserved for system use (particularly the double under-scored variety) and (2) they’re ugly anyway.

If you look at the sort of code generated by the CInterop tool for Kotlin Native, then it’s full of leading underscores so the tool can be confident that it’s not going to clash with any other identifiers used in the program. It’s as ugly as h*ll but it doesn’t matter as you wouldn’t normally see this stuff anyway.

1 Like

I was a little lazy with my question, my use case was actually exactly as @Wasabi375 had mentioned – as a backing property.
I’ve disabled the inspection, but it would be nice if the inspection could be left on and the IDE could tell whether or not it was a backing property, in which case I want the underscore.

This is still unclear in the style guide. Judging by the warning in IntelliJ, there is an implicit expectation that backing fields in objects should not use an underscore… however that difference between object and class is not explicitly stated anywhere in the style guide (or at least not where I can find it).

1 Like