Nikky
03/30/2020, 1:09 PMMike
03/30/2020, 1:11 PMMike
03/30/2020, 1:11 PMNikky
03/30/2020, 1:18 PMMike
03/30/2020, 1:23 PMdata class
is fairly restricted, and seems to be intended for simple POJO's. It allows mutable properties, but is best suited to immutable.
I suspect if you require a var
, then you use a regular class.
Alternatively, use an immutable data class, and a helper method that leverages copy
and has the pre-checks. Obviously not as efficient as a regular setter, but if your app isn't super performance constrained, it's an alternative approach.Michael de Kaste
03/30/2020, 1:27 PMfun main(){
val test1 = Class(-1)
println(test1)
val test2 = Class(1)!!
println(test2)
test2.test = 3
println(test2)
test2.test = -1
println(test2)
}
data class Class private constructor(
private var _test: Int
){
var test: Int
set(value) {if(value >= 0) _test = value}
get() = _test
companion object{
operator fun invoke(test: Int) = test.takeIf { it >= 0 }?.let { Class(it) }
}
}
This is already kind of hacky:
null
Class(_test=1)
Class(_test=3)
Class(_test=3)
Nikky
03/30/2020, 7:58 PMMichael de Kaste
03/31/2020, 12:20 PMNikky
03/31/2020, 9:09 PMMichael de Kaste
04/01/2020, 9:21 AMNikky
04/01/2020, 1:34 PM