https://kotlinlang.org logo
Title
g

Gyuhyeon

12/04/2019, 6:45 AM
So.. when we declare a getter for a field in Kotlin, there's no way to just directly call the field privately?
class MembershipInfo {
    var birthday: String? = null
        get() = if (field.isNullOrBlank() && birthdayEnc.isNotNullOrBlank()) {
            field = birthdayEnc.let {
                AesEncryptor.decryptText(it)
            }
            field
        } else {
            field
        }
    var birthdayEnc: String? = null
        get() = if (field.isNullOrBlank() && birthday.isNotNullOrBlank()) {
            field = birthday.let {
                AesEncryptor.encryptText(it)
            }
            field
        } else {
            field
        }
}
this code is giving me a wonderful stack overflow error when both fields are set as null. apparently, calling birthdayEnc.isNotNullOrBlank() calls birthdayEnc's getter instead of accessing it directly. This is calling from WITHIN the class, this seems like a design oversight ._. any workarounds?
k

Kroppeb

12/04/2019, 6:48 AM
If you want to give private access to the backing field, you could make a separate private field and use that one instead of a hidden backing field
g

Gyuhyeon

12/04/2019, 7:39 AM
I ended up with moving the encryption logic to the setter instead of the getter, thanks
class MembershipInfo {
    var birthday: String? = null
        set(value) {
            field = value
            if (birthdayEnc.isNullOrBlank()) {
                birthdayEnc = value?.run { AesEncryptor.encryptText(value) }
            }
        }
    var birthdayEnc: String? = null
        set(value) {
            field = value
            if (birthday.isNullOrBlank()) {
                birthday = value?.run { AesEncryptor.decryptText(value) }
            }
        }
}