Using “m” prefix for variables in Kotlin

99封情书 提交于 2019-12-03 16:36:31

问题


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
}


来源:https://stackoverflow.com/questions/48056248/using-m-prefix-for-variables-in-kotlin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!