Вопрос:

Using "m" prefix for variables in Kotlin

java android kotlin coding-style

1964 просмотра

3 ответа

1885 Репутация автора

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?

Автор: Hugo Passos Источник Размещён: 02.01.2018 06:06

Ответы (3)


14 плюса

3766 Репутация автора

Решение

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

Автор: Yuri Schimke Размещён: 02.01.2018 06:09

9 плюса

111900 Репутация автора

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.

Автор: ianhanniballake Размещён: 02.01.2018 06:10

4 плюса

33768 Репутация автора

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
}
Автор: s1m0nw1 Размещён: 02.01.2018 07:43
Вопросы из категории :
32x32