Hello folks. I'd like to know if there's a way of ...
# announcements
c
Hello folks. I'd like to know if there's a way of passing a Named parameter as an argument. For exemple: fun abc(namedArgument: String, value: Int) { abcd(namedArgument = value) } Thanks in advance 👍
g
Nope, it's not possible to do without reflections
because there is no compile time guarantee that named argument name is valid
c
Got it. Is it a limitation on the JVM side or on Kotlin's?
g
Both
Kotlin and Java are type safe languages, you cannot call an arbitrary overload of function without reflections
👍 1
c
Okay. Well I guess I'll have to find another approach haha Thanks so much @gildor
g
Maybe you could show some example what you are trying to achieve
c
Oh sure. Well, I'm using the new Android Proto Data store and it doesn't receive an id anymore. Values to be updated used to be identified by ids. So, those would be passed to the shared preferences manager along with their new values. But now It updates only the parameters identified with a named parameter. The point is that I'd like to abstract that. For example: Here's the gist of what i'm trying to do: https://gist.github.com/caiodev/0b027196388aa43d074d7a41f487ce8a At line 39, i'd like to abstract the whole lambda and only pass the value i want to update, but that's not possible because to do that i'd need to pass the parameter name along with the value. I could create a method that would return a
Copy code
protoDataStore.updateData
context to me but i still would have to call
Copy code
userPref.copy()
everytime i had to update a value. But since it needs a named parameter, right now, i would have to repeat this code everywhere i call it. That's why i asked if there was a way to pass named parameters as arguments because that way, the code would look cleaner. In my mind it would look like something like this:
Copy code
fun <T> updateValue(namedParameter: String, value: T) {
    protoDataStore.updateData { userPref ->
        userPref.copy(namedParameter = value)
    }
}
Oh, don't mind my activity full of things that shouldn't be there. I was just doing a POC 😁
The temporary solution would be like this. This is the method:
Copy code
private suspend fun returnUpdateDataContext(instruction: UserPreferences): UserPreferences =
    protoDataStore.updateData {
        instruction
    }
And its call would be like this:
Copy code
returnUpdateDataContext (
    protoDataStore.data.first().copy(name = "unkn0wn")
)
That works but the problem is that i still have to repeat the
Copy code
.copy()
block
g
I think use
copy()
is really the only good option for this case, it’s type safe after all
👍 1