0

I want to transform my java POJO class to kotlin data class. But I m not able to write constructor to accept an array.

public class myClass {

    private String department;

    private employee[] data;

}

2 Answers 2

1

You can create a class like this:

data class MyClass(
    val department: String? = null,
    val data: Array<Employee>? = null
)
Sign up to request clarification or add additional context in comments.

Comments

1

Write a data class, which will generate several things for you including a constructor and just give it an Array<Employee>:

/**
 * A data class accepting an array of employees as constructor argument
 */
data class MyClass(val department: String, val employees: Array<Employee>)

/**
 * Dummy class to make this work
 */
data class Employee(val name: String)

/**
 * Main function
 */
fun main() {
    // create an array of employees
    var a1 = Array(5) {
        Employee("Mister Money");
        Employee("Monsieur Monétaire");
        Employee("Señor Dinero");
        Employee("Herr Geld");
        Employee("Signore denaro")
    }

    // and pass it to a new instance of Employee
    val myInstance = MyClass("Finance", a1)

    // then print that instance
    println(myInstance)
}

Output of printing the created instance of MyClass:

myClass(department=Finance, employees=[Employee(name=Signore denaro), Employee(name=Signore denaro), Employee(name=Signore denaro), Employee(name=Signore denaro), Employee(name=Signore denaro)])

Comments

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.