Kotlin data class copy function not working

倾然丶 夕夏残阳落幕 提交于 2019-12-04 11:21:18

Okay, I missed this sentence in the docs:

If any of these functions is explicitly defined in the class body or inherited from the base types, it will not be generated.

Which, infact, makes copy no better than a constructor for Java interop.

What you can do to get around the limitations of Kotlin's copy(), is to create your own copy function inside your data class. Example below:

data class User(val name : String, val property: String) {

    fun copy() : User {
      //uses the fields name and property defined in the constructor
      return User(name,property)
    }

    //or if you need a copy with a changed field
    fun copy(changedProperty : String) : User {
      return User(name, changedProperty)
    }

}

For interop with java you can make function that use kotlin generated .copy

@Entity
data class User(@PrimaryKey var id: Int = 0,
            var firstName: String? = null,
            var lastName: String? = null,
            var phone: String? = null,
            var email: String? = null,
            var phoneCode: String? = null,
            var tokenId: String? = null,
            var provider: SocialProvider? = null) : Serializable {


var countryCodeIso: String? = null
    set(countryCodeIso) {
        if (countryCodeIso != null) {
            field = countryCodeIso.toLowerCase()
        }
    }

fun javaCopy(): User {
    val user = copy()
    user.countryCodeIso = countryCodeIso
    return user
}}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!