问题
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?
回答1:
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
来源:https://stackoverflow.com/questions/59966334/what-are-underscore-names-in-kotlin-reserved-for