The variable naming rules in Kotlin are similar to those in Java, as both languages follow the same naming conventions. Here are some of the key rules for naming variables in Kotlin or Java:
- Variable names must begin with a letter (a-z or A-Z) or an underscore (
_
). - Variable names can contain letters, digits, and underscores.
- Variable names are case sensitive, meaning that
myVariable
andmyvariable
are considered to be two different variables. - Variable names should be descriptive and should reflect the purpose of the variable.
- Variable names should not be a reserved keyword or a class name.
- Here are some examples of valid and invalid variable names:
// Valid variable names
val firstName: String = "John"
var userAge: Int = 30
val _myVariable: Boolean = true
// Invalid variable names
val 1stName: String = "Alice" // cannot start with a digit
val last-name: String = "Doe" // cannot contain a hyphen
val if: String = "condition" // cannot use a reserved keyword