简体   繁体   中英

How to use setter for this Kotlin class property?

I have the following class coded in Kotlin:

class MyClass {
    var color: String = ""
    var action: String = ""
    val owners = Array(1) {Owner()}

    class Owner {
        var userId: String = ""
        var userName: String = ""
    }
}

...and I'm accessing it Java:

MyClass myObject = new MyClass();
myObject.setColor("blue");
myObject.setAction("throw");

...and I'd like to be able to set the owner. I'm not sure how, though. If it were an object that was coded in Java with public members, I'd just do something like:

myObject.owners[0].userId = "001";
myObject.owners[0].userName = "Freddy"

Since the object was coded in Kotlin, I need to user a setter in Java.

How do I set the properties in the first element of an array with a setter?

Use getOwners which will return owners object then set the value.

myObject.getOwners()[0].setUserId("001");
myObject.getOwners()[0].setUserName("Freddy");

For each Kotlin property foo , you can call its getter in Java as getFoo() and, if the property is mutable, the setter as setFoo(value) .

See: Calling Kotlin from Java — Properties

In your case, just access the array with the getter, take its item and call the setters: myObject.getOwners()[0].setUserId("001"); and myObject.getOwners()[0].setUserName("Freddy"); , or assign the Owner to a local variable:

MyClass.Owner owner = myObject.getOwners()[0];
owner.setUserId("001");
owner.setUserName("Freddy");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM