I’m trying out the new Context Parameters feature....
# language-proposals
a
I’m trying out the new Context Parameters feature. They can be used on properties, but seems the context applies to both the getter and setter. Would it make sense to be able to specify different context for getter and setter? For example, I have
Preferences
and
MutablePreferences
, and the context for
get()
should be
Preferences
, and the context for
set(value)
should be
MutablePreferences
y
You could duplicate it maybe:
Copy code
context(l: List<T>)
@set:Deprecated("", level = DeprecationLevel.HIDDEN)
var <T> first get() = l.first()
set(value) { TODO() }
context(l: MutableList<T>)
@get:JvmName("getMutFirst")
@set:JvmName("setMutFirst")
@get:Deprecated("", level = DeprecationLevel.HIDDEN)
var <T> first get() = l.first()
set(value) { l[0] = value }

fun main() = with(listOf(1)) {
    println(first)
    with(mutableListOf(1)) {
    	println(first)
        first = 2
    	println(first)
	}
}
🪄 2
a
Never would have thought of that, thanks
y
I can't guarantee that this will always continue working of course. In fact, the first one had to be a
var
because otherwise it caused issues.
h
Shouldn’t it be possible with an extension?
a
@hfhbd this could work, but notice code duplication in `get`:
Copy code
val Preferences.serverAddress: ServerAddress?
    get() = get(Keys.SERVER_HOST)
        ?.let { ServerAddress(it) }

var MutablePreferences.serverAddress: ServerAddress?
    set(serverAddress) {
        if (serverAddress == null || serverAddress.value.isEmpty()) {
            remove(Keys.SERVER_HOST)
        } else {
            set(Keys.SERVER_HOST, serverAddress.value)
        }
    }
    get() = get(Keys.SERVER_HOST)
        ?.let { ServerAddress(it) }
Preferences
and
MutablePreferences
are from jetpack DataStore, an external lib
y
Copy code
val Preferences.serverAddress: ServerAddress?
    get() = get(Keys.SERVER_HOST)
        ?.let { ServerAddress(it) }

var MutablePreferences.serverAddress: ServerAddress?
    set(serverAddress) {
        if (serverAddress == null || serverAddress.value.isEmpty()) {
            remove(Keys.SERVER_HOST)
        } else {
            set(Keys.SERVER_HOST, serverAddress.value)
        }
    }
    get() = (this as Preferences).serverAddress
👍 1
a
That’s great, thanks everyone
e
one slight tweak and you can avoid the explicit cast
Copy code
val Preferences.serverAddress: ServerAddress?
    get() { ... }

var MutablePreferences.serverAddress: ServerAddress?
    get() = run(Preferences::serverAddress)
    set(value) { ... }
👍 1