I have a kotlin data class and I'm trying to call it from Java method.
data class Item (
@PrimaryKey(autoGenerate = true) var var1: Long? ,
@ColumnInfo(name ="var1") var var2: Long){}
From Java , I'm trying to save a list of Item so I need to instance Data class. I don't understand how I can do it.
As a quick refresher, Kotlin is a modern, statically typed language that compiles down for use on the JVM. It's often used wherever you'd reach for Java, including Android apps and backend servers (using Java Spring or Kotlin's own Ktor).
Thus if one can derive the bytecode of compiled Kotlin file, it can be decompiled in order to produce the equivalent Java code. Android Studio does exactly the same to carry out the code conversion from Kotlin to Java.
But Kotlin provides a unique way to declare a POJO class by introducing the "data" keyword. It can be applied along with class. Once a class is defined as data class, the Kotlin compiler itself will be creating all the supporting getter() and setter() methods for this class.
Instantiating a data class
is not different from instatiating a "normal" Kotlin class.
From your Java code, you instantiate it as if it were a Java class:
Item item = new Item(1L, 2L);
Just for reference, a data class
is a class
that automatically gets the following members (see documentation here):
equals()
/hashCode()
pair;toString()
of the form "MyClass(field1=value1, field2=value2)";componentN()
functions corresponding to the properties in their order of declaration; this can be useful for destructuring declarations, such as:
data class Item(val val1: Long, val val2: Long)
fun main(args: Array<String>) {
val item = Item(1L, 2L)
val (first, second) = item
println("$first, $second")
}
This will print: 1, 2
copy()
function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With