Kotlin变量是否应沿用Android的m前缀命名?求新规范指引
m Prefix Convention) Great question! Making the switch from Java to Kotlin often means unlearning small habits like the m prefix for member variables—and it totally makes sense to feel confused at first. Let’s break down how to align your variable naming with Kotlin’s conventions.
First: Kotlin’s Core Naming Philosophy
Kotlin prioritizes simplicity and readability by eliminating boilerplate. Unlike Java, where you needed m prefixes to distinguish private member fields from local variables (and then wrapped them in getters/setters), Kotlin handles this automatically.
The official Kotlin style guide explicitly recommends avoiding prefixes like m or s for class properties. Instead, use direct, meaningful names in camelCase (starting with a lowercase letter).
Fixing Your Example
Let’s adjust your Kotlin code to follow conventions:
Java (Original, Still Valid)
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 (Convention-Friendly Version)
// Use var if the property is mutable, val if it's read-only data class Foo(var name: String) fun main(args: Array<String>) { val foo = Foo("Initial Name") // Data classes require constructor args foo.name = "Foo" // Clean, natural access—no m prefix needed! }
Here’s why this works:
- When you define
var name: String, Kotlin automatically generates a private backing field (you don’t need to see or name it) and the corresponding getter/setter methods. - In Kotlin, accessing
foo.nameis syntactic sugar for calling the getter/setter—so you get the encapsulation of Java without the clutter of prefixes.
What If You’re Mixing Java and Kotlin?
If you’re working in a mixed codebase:
- Keep existing Java code with
mprefixes (no need to rewrite it unless you want to). - Kotlin can seamlessly interact with Java’s getter/setter methods: for a Java class with
setName()andgetName(), Kotlin lets you writefoo.name = "Foo"instead of calling the Java methods directly. - If you need to expose a Kotlin property to Java with a specific name (e.g., to match an old
m-prefixed field), you can use annotations like@get:JvmNameor@JvmField, but this should be a rare edge case.
Key Takeaways for Kotlin Naming
- No prefixes: Ditch
m,s, or any other prefixes for class properties. - CamelCase: Use lowercase starting letters for properties (e.g.,
userName,totalCount). varvsval: Usevarfor mutable properties (can be changed) andvalfor read-only properties (like Java’sfinal).
内容的提问来源于stack exchange,提问作者Hugo Passos

