使用"m"表示Kotlin中变量的前缀 [英] Using "m" prefix for variables in Kotlin

查看:580
本文介绍了使用"m"表示Kotlin中变量的前缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在编程中(通常是在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

特殊的前缀或后缀,例如在示例name_中看到的, 除了在支持的情况下,不使用mName,s_name和kName 属性(请参见"支持属性").

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

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").

这篇关于使用"m"表示Kotlin中变量的前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆