Manoj Perumarath
Manoj Perumarath

Reputation: 10214

Why does Kotlin data class objects have backticks?

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.

Upvotes: 6

Views: 1127

Answers (3)

Ori Marko
Ori Marko

Reputation: 58772

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

Upvotes: 5

Manoj Perumarath
Manoj Perumarath

Reputation: 10214

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.

Upvotes: 0

Eugene Babich
Eugene Babich

Reputation: 1699

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

Upvotes: 2

Related Questions