Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are underscore names in Kotlin reserved for?

Tags:

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

What are they reserved for? What is their function?

like image 275
ZeitPolizei Avatar asked Jan 29 '20 11:01

ZeitPolizei


People also ask

What does ?: Mean in Kotlin?

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.

Why we use underscore in variable names?

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.

What does an underscore before a variable name mean?

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.

Can you start a variable name with _?

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 _ )


Video Answer


1 Answers

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 
like image 57
hotkey Avatar answered Jan 03 '23 09:01

hotkey