gpt4 book ai didi

kotlin - Kotlin 中的下划线名称是为什么保留的?

转载 作者:行者123 更新时间:2023-12-02 12:16:00 25 4
gpt4 key购买 nike

在 Python 中你可以使用 _作为变量名。如果我写例如val _ = 3在 Kotlin IntelliJ 中给我一个错误:

Names _, __, ___, ..., are reserved in Kotlin

它们是用来做什么的?它们的作用是什么?

最佳答案

单下划线已经以多种方式使用,您希望跳过参数或组件并且不想给它命名:

  • 对于 ignoring parameters in lambda expressions :
    val l = listOf(1, 2, 3)
    l.forEachIndexed { index, _ -> println(index) }
  • 对于 unused components in destructuring declarations :
    val p = Pair(1, 2)
    val (first, _) = p
  • 用于忽略 try - catch 语句中的异常:
    try {
    /* ... */
    } catch (_: IOException) {
    /* ... */
    }

  • 这些语法形式是在 Kotlin 1.1 中引入的,这就是为什么在 Kotlin 1.1 之前保留下划线名称的原因。像 _____ 这样的多下划线名称也被保留了,这样它们就不会在以前使用单下划线名称的地方被滥用。

    正如 @Willi Mentzela comment 中所指出的,下划线的另一种用法是 separating digit groups in numeric literals ,尽管不在标识符的位置:
    val oneMillion = 1_000_000
    val creditCardNumber = 1234_5678_9012_3456L

    关于kotlin - Kotlin 中的下划线名称是为什么保留的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59966334/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com