Kotlin: single property with multiple setters of d

2019-04-21 16:33发布

问题:

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?

回答1:

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()
    }
}


回答2:

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))
}


标签: kotlin