Search code examples
javaandroidkotlindata-class

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.


Solution

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