Gerard Bosch
02/25/2021, 6:21 PMdata 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!Gerard Bosch
02/25/2021, 6:26 PMfun myProperty(): BigDecimal = fxFeePercentage ?: BigDecimal.ZERO
randomcat
02/25/2021, 6:29 PMrandomcat
02/25/2021, 6:29 PMGerard Bosch
02/25/2021, 6:29 PMGerard Bosch
02/25/2021, 6:29 PMrandomcat
02/25/2021, 6:29 PMGerard Bosch
02/25/2021, 6:30 PMrandomcat
02/25/2021, 6:30 PMrandomcat
02/25/2021, 6:30 PMGerard Bosch
02/25/2021, 6:31 PMGerard Bosch
02/25/2021, 6:31 PMrandomcat
02/25/2021, 6:32 PMnkiesel
02/25/2021, 6:33 PMimport 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
}
Gerard Bosch
02/25/2021, 6:36 PMnkiesel
02/25/2021, 6:36 PMval myProperty: BigDecimal = _myProperty ?: BigDecimal.ZERO
if the fallback value is constantGerard Bosch
02/25/2021, 6:37 PMMarc Knaup
02/25/2021, 6:38 PMnull
values to 0
, so you could just provide a factory:
data class MyDataClass(val myProperty: BigDecimal)
fun MyDataClass(myProperty: BigDecimal?) =
MyDataClass(myProperty ?: BigDecimal.ZERO)
nkiesel
02/25/2021, 6:38 PMMarc Knaup
02/25/2021, 6:39 PMcopy()
with nullable myProperty
then you have to add your own copy()
extension function too.