Using “m” prefix for variables in Kotlin

2020-06-02 05:43发布

问题:

Using "m" prefix for variable names became usual in programming, mainly in Android, but since Kotlin arrived, this minor thing bothers me a bit.

Setting and getting variables with "m" prefix doesn't seem really nice, because in Java we create (and name) our setters and getters, so we can omit the "m", but this doesn't happen in Kotlin, unless we walk in the opposite of conventions and repeat Java's technique.

Java:

public class Foo {
    private String mName;

    public void setName(String name) {
        mName = name;
    }

    public String getName() {
        return mName;
    }
}

public class Main {
    public static void main(String[] args) {
        Foo foo = new Foo();
        foo.setName("Foo");
    }
}

Kotlin:

data class Foo(val mName: String)

fun main(args: Array<String>) {
    val foo = Foo()
    foo.mName = "Foo"  // "m" prefix doesn't fit
}

What should we do? Is there a new convention to follow?

回答1:

A good reference from Android

https://android.github.io/kotlin-guides/style.html

Special prefixes or suffixes, like those seen in the examples name_, mName, s_name, and kName, are not used except in the case of backing properties (see “Backing properties”).



回答2:

Per the Android Kotlin Style Guide:

Special prefixes or suffixes, like those seen in the examples name_, mName, s_name, and kName, are not used except in the case of backing properties (see “Backing properties”).

Therefore you should not use the "m" prefix for variables in Kotlin.



回答3:

I actually don’t think it’s good practise to have prefixed variables in the public API, thus foo.mName = "Foo" would be undesirable. For private fields this would be acceptable though.

The official conventions for the Kotlin language say:

Names for backing properties

If a class has two properties which are conceptually the same but one is part of a public API and another is an implementation detail, use an underscore as the prefix for the name of the private property:

class C {
    private val _elementList = mutableListOf<Element>()

    val elementList: List<Element>
         get() = _elementList
}