Given the discussion that took place : Click
Finally , This method received the most scores :
var x = 10
var y = 20
fun main() {
println("x=$x, y=$y") // x=10, y=20
swap(::x, ::y)
println("x=$x, y=$y") // x=20, y=10
}
fun <T> swap(firstRef: KMutableProperty0<T>, secRef: KMutableProperty0<T>) {
val temp = firstRef.get()
firstRef.set(secRef.get())
secRef.set(temp)
}
But as one user commented at that time, this method gives me the following error: “References to variables and parameters are unsupported.”
Do we still have this problem in Kotlin and there is no solution??[I’m new to Kotlin]
1
That works with properties, not local variables. And you need to have imported the reflection library. And furthermore, this strictly answered the question the OP posed without mentioning that it is not something you would typically do in general application code. If you’re using reflection as someone new to OOP or strongly typed languages, you probably have a fundamental misunderstanding of how to use the language. Reflection is rarely used outside of building specific code libraries that do powerful code modification and generation.
The correct way to swap variables in Kotlin is in one of the other answers on that question, the one that uses the also
scope function.
The OP of that question wanted to write a function that modifies what references some properties/variables are using. This is basically like pointer manipulation in lower level languages. It’s typically not recommended in a higher level, strongly typed objected oriented language like this. Poor encapsulation and separation of concerns, among other issues. But there are cases where you might write functions that take mutable classes as parameters and do something to them. It just wouldn’t normally happen in general-purpose sorts of functions.
You asked if Kotlin “still has this problem”, but it is not considered a problem, since it’s something you typically shouldn’t do. So, it’s not something that will ever be “solved”.
3