In Python you can use _
as a variable name. If I write e.g. val _ = 3
in Kotlin IntelliJ gives me an error with:
Names _, __, ___, ..., are reserved in Kotlin
What are they reserved for? What is their function?
In certain computer programming languages, the Elvis operator ?: is a binary operator that returns its first operand if that operand is true , and otherwise evaluates and returns its second operand.
The underscore in variable names is completely optional. Many programmers use it to differentiate private variables - so instance variables will typically have an underscore prepended to the name. This prevents confusion with local variables.
An underscore in front usually indicates an instance variable as opposed to a local variable. It's merely a coding style that can be omitted in favor of "speaking" variable names and small classes that don't do too many things. Follow this answer to receive notifications.
Go variable naming rules: A variable name must start with a letter or an underscore character (_) A variable name cannot start with a digit. A variable name can only contain alpha-numeric characters and underscores ( a-z, A-Z , 0-9 , and _ )
The single underscore is already used in several ways where you want to skip a parameter or a component and don't want to give it a name:
For ignoring parameters in lambda expressions:
val l = listOf(1, 2, 3)
l.forEachIndexed { index, _ -> println(index) }
For unused components in destructuring declarations:
val p = Pair(1, 2)
val (first, _) = p
For ignoring an exception in a try
-catch
statement:
try {
/* ... */
} catch (_: IOException) {
/* ... */
}
These syntax forms were introduced in Kotlin 1.1, and that's why the underscore names had been reserved before Kotlin 1.1. The multiple-underscore names like __
, ___
had also been reserved so that they are not misused where previously one would have used a single-underscore name.
As @Willi Mentzel noted in a comment, another use of underscores, though not in a position of an identifier, is separating digit groups in numeric literals:
val oneMillion = 1_000_000
val creditCardNumber = 1234_5678_9012_3456L
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With