Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 255
Manoj Perumarath Avatar asked Nov 20 '19 12:11

Manoj Perumarath


People also ask

What are Backticks in Kotlin?

The backtick are a "workaround" to allow you to call methods that have a name representing a Kotlin keyword. See kotlinlang: Some of the Kotlin keywords are valid identifiers in Java: in, object, is, etc.

Can Kotlin data class have methods?

Data classes specialize in holding data. The Kotlin compiler automatically generates the following functionality for them: A correct, complete, and readable toString() method. Value equality-based equals() and hashCode() methods.

What is Dataclass in Kotlin?

A Kotlin Data Class is used to hold the data only and it does not provide any other functionality apart from holding data. There are following conditions for a Kotlin class to be defined as a Data Class: The primary constructor needs to have at least one parameter.


2 Answers

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

like image 66
user7294900 Avatar answered Oct 02 '22 01:10

user7294900


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

like image 28
Zhebzhik Babich Avatar answered Oct 02 '22 01:10

Zhebzhik Babich