Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data class Kotlin to Java Class

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.

like image 513
Younes Ben Tlili Avatar asked Mar 05 '18 13:03

Younes Ben Tlili


People also ask

Can I use Kotlin data class in Java?

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).

Can we convert Kotlin code to Java?

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.

How do you make a POJO class in Kotlin?

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.


1 Answers

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.

like image 88
user2340612 Avatar answered Sep 18 '22 23:09

user2340612