Kyrylo Liubun
Kyrylo Liubun

Reputation: 2135

Kotlin delegate all fields by class property

I have a wrapper class Manager that has a property managerInfo of type UserInfo that I can’t modify. The wrapper class just add business rules around the info object. In code I need to access properties of the managerInfo and write each time manager.managerInfo.username is a little verbose.

I know that I can delegate property to this info object like that:

class Manager {
...
    val username by UserInfo
...
}

And then I can simply do manager.username. But the problem is that the info class has about 15 properties and do this manually will be messy.

Is there is way to delegate all properties by means of Kotlin lang or by some library?

Upvotes: 3

Views: 1702

Answers (1)

hluhovskyi
hluhovskyi

Reputation: 10106

You can do implementation by delegation, which looks like this:

interface UserCommon {
    val username: String
    val email: String
}

data class UserInfo(
        override var username: String,
        override var email: String
) : UserCommon

class Transaction(
        userInfo: UserInfo
) : UserCommon by userInfo

After that class Transaction will have all properties that UserCommon does, but implementation is delegated to userInfo which is passed to constructor.

The other way is to convert UserInfo to MutableMap and delegate property invocation to that map:

class Transaction(
    userInfoMap: HashMap<String, Any>
) {
    var username: String by userInfoMap
    var email: String by userInfoMap
}

Upvotes: 5

Related Questions