What are underscore names in Kotlin reserved for?

时光怂恿深爱的人放手 提交于 2020-07-15 09:26:17

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!