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
预订的是什么?它们的功能是什么?
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
预订的是什么?它们的功能是什么?
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:
ignoring parameters in lambda expressions美元:
val l = listOf(1, 2, 3)
l.forEachIndexed { index, _ -> println(index) }
对于忽略try
-catch
语句中的异常:
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