Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: single property with multiple setters of different types

Tags:

kotlin

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?

like image 946
sva605 Avatar asked Sep 11 '17 10:09

sva605


People also ask

What is get () in Kotlin?

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.

What are Kotlin's properties?

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.

Should you use getters and setters in Kotlin?

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.

What is backing property in Kotlin?

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.


2 Answers

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()
    }
}
like image 141
sva605 Avatar answered Sep 29 '22 05:09

sva605


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))
}
like image 33
guenhter Avatar answered Sep 29 '22 05:09

guenhter