问题描述
在编程中(通常是在Android中)使用变量名的前缀"m"已成为常见现象,但是自Kotlin到来以来,这件小事使我有些烦恼.
设置和获取带有"m"前缀的变量似乎不太好,因为在Java中,我们创建(和命名)了setter和getter,因此我们可以省略"m",但这在Kotlin中不会发生,除非我们走惯于约定的相反之处并重复Java的技术.
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");
}
}
科特琳:
data class Foo(val mName: String)
fun main(args: Array<String>) {
val foo = Foo()
foo.mName = "Foo" // "m" prefix doesn't fit
}
我们该怎么办?有新的约定要遵循吗?
Android的良好参考
https://android.github.io/kotlin-guides/style.html
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?
A good reference from Android
https://android.github.io/kotlin-guides/style.html
这篇关于使用"m"表示Kotlin中变量的前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!