Why does Kotlin data class objects have backticks?

╄→гoц情女王★ 提交于 2021-01-27 07:57:31

问题


This is my data class created using a Kotlin data class creator Plugin.

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

This code gets work even if I remove the backticks, I wonder if it's for Java interoperability. But this variable is not a keyword but also it has backticks. why? Based on Why does this Kotlin method have enclosing backticks? this question is is a keyword for both Java and Kotlin but data is not.


回答1:


You can use backticks simply to enclose class, method or variable name

For example it's useful if there are spaces:

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

Or as you mention if using Kotlin keyword

If a Java library uses a Kotlin keyword for a method

foo.`is`(bar)

data is a 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

And not a Hard Keyword that can't be used as identifier

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




回答2:


It allows you to use reserved keywords and operators as names of your variables. The list of those words: https://kotlinlang.org/docs/reference/keyword-reference.html




回答3:


Based on this question's answerWhy does this Kotlin method have enclosing backticks? and the comments from @forpas and @marstran I was able to understand my problem.

The is keyword is a hard keyword

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

so fore interoperability we need to use backticks because Java and Kotlin both have is keyword.

Where data keyword is only available in Kotlin and also belong to the category

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

So we can use it with or without backticks.

Also as an additional note you can use bacticks to customize your identifier

var `data is simple` : List<String>

If it shows lint error use

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



来源:https://stackoverflow.com/questions/58954821/why-does-kotlin-data-class-objects-have-backticks

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