Hi there! I'm trying to find if is possible in Kot...
# announcements
g
Hi there! I'm trying to find if is possible in Kotlin to define a custom accessor for a class or data class that simply returns the non-nullable version of a class field (using a fallback value). Can't figure out how the syntax would be for the following:
Copy code
data class MyDataClass(private val myProperty: BigDecimal?) {
            val myProperty: BigDecimal = myProperty 
                get() = field ?: BigDecimal.ZERO       // <-- I want to just expose the non-nullable version of the property
        }
👆 I've just tried the above as per what I could grasp from https://kotlinlang.org/docs/properties.html#getters-and-setters but can't make it work 😬 Is that possible to redefine a property accessor in such way? If it is, which syntax/construct should achieve it? Thx!
I could to it using a function in the body of the class, but I would like to know if it is possible to do so using the same property as at call-site can be seen as a property instead of function call
Copy code
fun myProperty(): BigDecimal = fxFeePercentage ?: BigDecimal.ZERO
r
no, it's not
you would need to pick a different name
g
Ohh 😞 I thought that, but was not sure
Thanks!
r
np
g
So probably the function approach suits me better then
r
I wouldn't do that with the exact same name either even if it's possible
at some point you'll type one and mean the other and you'll have a bad day
g
The property is private, just want to expose it as non-nullable with a default value
I've just got an idea! Maybe I can use a default value in the constructor, that would work for my case I think
r
depends on the semantics you want
n
Copy code
import java.math.BigDecimal

data class MyDataClass(private val _myProperty: BigDecimal?) {
    val myProperty: BigDecimal
        get() = _myProperty ?: BigDecimal.ZERO
}

fun main() {
    val p1: BigDecimal = MyDataClass(BigDecimal(22)).myProperty
    val p2: BigDecimal = MyDataClass(null).myProperty
    println("p1=$p1 p2=$p2")  // prints p1=22 p2=0
}
g
Thanks for the naming idea @nkiesel - I'm totally new to Kotlin, but I see what you mean, should perfectly work as well
n
this could even use
val myProperty: BigDecimal = _myProperty ?: BigDecimal.ZERO
if the fallback value is constant
g
👍 thx 🙂 🙂
m
Ideally data classes don’t change/compute their properties after creation. Looks like you want to default
null
values to
0
, so you could just provide a factory:
Copy code
data class MyDataClass(val myProperty: BigDecimal)

fun MyDataClass(myProperty: BigDecimal?) =
    MyDataClass(myProperty ?: BigDecimal.ZERO)
n
only downside is that this then means the class has 2 fields instead of 1. Classical space/time trade-off
m
If you also need a
copy()
with nullable
myProperty
then you have to add your own
copy()
extension function too.