I'm trying to build a class that has a property of LocalDate
type which has setters that accept different types: LocalDate
or String
. In case of LocalDate
, the value gets assigned directly, in case of String
, it gets parsed and then assigned.
In Java, I just need to implement two overloaded setters handling both of above mentioned cases. But I have no idea how to handle that in Kotlin. I have tried this:
class SomeExampleClass(var _date: LocalDate) {
var date = _date
set(value) {
when(value) {
is LocalDate -> value
is String -> LocalDate.parse(value)
}
}
}
It doesn't compile. How can I resolve such a problem?
In Kotlin, setter is used to set the value of any variable and getter is used to get the value. Getters and Setters are auto-generated in the code. Let's define a property 'name', in a class, 'Company'. The data type of 'name' is String and we shall initialize it with some default value.
Properties are the variables (to be more precise, member variables) that are declared inside a class but outside the method. Kotlin properties can be declared either as mutable using the “var” keyword or as immutable using the “val” keyword. By default, all properties and functions in Kotlin are public.
In programming, getters are used for getting value of the property. Similarly, setters are used for setting value of the property. In Kotlin, getters and setters are optional and are auto-generated if you do not create them in your program.
A Backing Field is just a field that will be generated for a property in a class only if it uses the default implementation of at least one of the accessors. Backing field is generated only if a property uses the default implementation of getter/setter.
After some time I returned to the problem of overloaded setters and developed the following solution:
class A(_date: LocalDate) {
var date: Any = _date
set(value) {
field = helperSet(value)
}
get() = field as LocalDate
private fun <T> helperSet(t: T) = when (t) {
is LocalDate -> t
is String -> LocalDate.parse(t)
else -> throw IllegalArgumentException()
}
}
So if you just want to construct it (via constructor
), just create a secondary constructor
SomeExampleClass(LocalDate.MAX)
SomeExampleClass("2007-12-03")
class SomeExampleClass(var _date: LocalDate) {
constructor(_date: String) : this(LocalDate.parse(_date))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With