11

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.

2 Answers 2

13

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Your data class will be like this :

       data class Item  (@PrimaryKey(autoGenerate = true) var var1: Long?,
            @ColumnInfo(name ="var1") var var2: Long);

From Java you can create create object like this:

  Item item=new Item(1L,2L);
   long firstValue=item.getVar1();
   long secondValue=item.getVar2();

If you want to create instance in kotlin it will be like:

   val item=Item(1L,2L);
    val firstValue:Long?=item.var1;
    val secondValue:Long?=item.var2;

2 Comments

Don't need semicolons in your kotlin examples.
Yes Semicolons are optional in Kotlin.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.