Sangmin Lee
06/24/2021, 5:47 AMclass CustomFieldTypeA() {
var value: String = ""
private val charset: Charset = ACharset()
}
class CustomFieldTypeB() {
var value: String = ""
private val charset: Charset = BCharset()
}
data class TestData(
var field1: CustomFieldTypeA = null,
var field2: CustomFieldTypeB = null,
)
The reason to use CustomFieldType is to have charset for string. And I want to use this type in the same way to use String like below
// for setter
val obj = TestData()
obj.field1 = "hi type 1"
obj.field2 = "hi type 2"
// for getter
val str = obj.field1
print(str) // hi type 1
Is there any way to do like this? (maybe using delegate?)Tobias Berger
06/24/2021, 7:21 AMgetValue
and setValue
operator functions in those classes and use them as delegates (var field1: String by CustomFieldTypeA()
)
Get more info on how to implement the delegate here: https://kotlinlang.org/docs/delegated-properties.htmlSangmin Lee
06/24/2021, 7:26 AMSangmin Lee
06/24/2021, 7:26 AMTobias Berger
06/24/2021, 7:28 AMSangmin Lee
06/24/2021, 7:48 AMTobias Berger
06/24/2021, 7:55 AM.value
to your calls when getting and setting the value.
BTW something else to think about: do you really need 2 different implementations or would it be enough to just have one implementation and provides the desired charset in the constructor?Tobias Berger
06/24/2021, 8:02 AMvar delegate1 = CustomFieldDelegateTypeA()
var field1: String by delegate1
2: this would be a simpler approach
var field1 = CustomFieldTypeA()
var value1: String
get() = field1.value
set(value) { field1.value = value }
Sangmin Lee
06/24/2021, 8:33 AMSangmin Lee
06/24/2021, 8:33 AMephemient
06/24/2021, 9:25 AMval container = Container(value = "")
var property by container::value