hfhbd
07/01/2022, 7:15 AMfun main() {
var s: String by Print {
"$this$this"
}
s = "foo"
println(s)
}
class Print<T : Any>(private val format: T.() -> String) : ReadWriteProperty<Nothing?, T> {
constructor(initial: T, formatter: T.() -> String) : this(formatter) {
value = initial
}
private lateinit var value: T
override fun getValue(thisRef: Nothing?, property: KProperty<*>): T = value
override fun setValue(thisRef: Nothing?, property: KProperty<*>, value: T) {
this.value = value
}
override fun toString(): String = value.format()
}
Joffrey
07/01/2022, 7:18 AMby
clausetoString
of the property s
to be overridden by that of the delegate?hfhbd
07/01/2022, 7:21 AMval sPrint = Print<String> { "$this$this" }
var s: String by sPrint
s = "foo"
println(sPrint)
println(s) // oops
But you could print the wrong variableJoffrey
07/01/2022, 7:58 AMtoString
from the delegatetoString()
, but that is not possible for every type, because you would need to return a custom subtype of the property typehfhbd
07/01/2022, 10:17 AMPrint<String>
, ideally I want to have String
. I think, I will use the first approach: Use a separate delegate variable and a custom detekt rule to prevent printing the primitive variable without the formatter.Joffrey
07/01/2022, 10:22 AMs
. You're just creating something on the side, so it should look like this - something on the side. For instance, something as simple as:
var s: String = "foo"
val formattedS: String get() = "$s$s"
hfhbd
07/01/2022, 10:26 AM