为什么 Kotlin 数据 class 对象有反引号?

Why does Kotlin data class objects have backticks?

这是我的数据 class 使用 Kotlin 数据 class 创建者插件创建的。

data class ResponseHealthInisghts(
val `data`: List<Data>,
val message: String,
val statusCode: Int
)

即使我删除了反引号,这段代码也能正常工作,我想知道它是否是为了 Java 互操作性。但是这个变量不是关键字,但它也有反引号。为什么? 基于 这个问题 is 是 Java 和 Kotlin 的关键字,但 data 不是。

它允许您使用保留关键字和运算符作为变量的名称。这些单词的列表:https://kotlinlang.org/docs/reference/keyword-reference.html

您可以使用反引号简单地括起 class、方法或变量名称

例如,如果有空格就很有用:

class `Final Frontier` {
    fun `out of space`() {
        val `first second`: String?
    }
}

或者如您所述,如果使用

If a Java library uses a Kotlin keyword for a method

foo.`is`(bar)

data 是一个 Modifier Keyword

data instructs the compiler to generate canonical members for a class The following tokens act as keywords in modifier lists of declarations and can be used as identifiers in other contexts

并且不是不能用作标识符的硬关键字

The following tokens are always interpreted as keywords and cannot be used as identifier

基于这个问题的回答 以及来自@forpas 和@marstran 的评论我能够理解我的问题。

is 关键字是 硬关键字

Hard Keywords are always interpreted as keywords and cannot be used as identifiers:

为了实现互操作性,我们需要使用反引号,因为 Java 和 Kotlin 都有 is 关键字。

其中data关键字仅在Kotlin中可用,也属于

类别

Soft Keywords act as keywords in the context when they are applicable and can be used as identifiers in other contexts.

因此我们可以在有或没有反引号的情况下使用它。

另请注意,您可以使用 bacticks 来自定义您的标识符

var `data is simple` : List<String>

如果显示 lint 错误使用

"File | Settings | Editor | Inspections | Illegal Android Identifier" and disable this inspection.