Issue
What is the equivalent property wrappers for Kotlin:
@propertyWrapper
struct Foo {
var wrappedValue: String {
get {
return "Test
}
}
}
@Foo var test: String
Solution
The accepted answer doesn't answer the question imo. Kotlin's property getters/setters are not sufficient to implement a property wrapper (which adds a layer of separation between code that manages how a property is stored and the code that defines a property according to https://docs.swift.org/swift-book/LanguageGuide/Properties.html). Delegated properties are the mechanism to achieve the same in Kotlin.
For the read-only example in the question, property wrappers don't really make sense, in Kotlin you would simply write (no need for delegates):
val test = "Test"
The example from https://docs.swift.org/swift-book/LanguageGuide/Properties.html is better suited to show the "equivalent" in Kotlin.
@propertyWrapper
struct TwelveOrLess {
private var number = 0
var wrappedValue: Int {
get { return number }
set { number = min(newValue, 12) }
}
}
@TwelveOrLess var height: Int
Above could be implemented like this in Kotlin:
var twelveOrLess: Int = 0
set(value) {
field = value.coerceAtMost(12)
}
var height by ::twelveOrLess
For more complex examples you could use a class to delegate to:
class TwelveOrLess(private val initValue: Int = 0) {
private var number = initValue
operator fun getValue(thisRef: Any?, property: KProperty<*>)= number
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Int) {
number = value.coerceAtMost(12)
}
}
var height by TwelveOrLess()
Answered By - Emanuel Moecklin
Answer Checked By - Willingham (JavaFixing Volunteer)