Kotlin:具有多个不同类型的setter的单个属性 [英] Kotlin: single property with multiple setters of different types

查看:196
本文介绍了Kotlin:具有多个不同类型的setter的单个属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个具有LocalDate类型属性的类,该类具有用于接受不同类型的设置程序:LocalDateString.在LocalDate的情况下,将直接分配值,在String的情况下,将对其进行解析然后分配. 在Java中,我只需要实现两个重载的setter来处理上述两种情况.但是我不知道如何在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?

推荐答案

一段时间后,我又回到了设置器超载的问题,并提出了以下解决方案:

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

这篇关于Kotlin:具有多个不同类型的setter的单个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆