[Idea] swap expression

Hello.
I have an idea like this

//i will use `obj` as example object
obj[a<-b] //i like this expression
or
obj[a->b]
or
obj[a:=b]

That will turn into

obj.swap(a,b)

a or b can be any type like this

obj[1 <- 2] into obj.swap(1,2)
obj["a" <- "b"] into obj.swap("a","b")

I’m not really sure why this would be needed. In my experience the only place where you really need swap is if you implement low level data structures, search algorithms, etc.
This is quite a small area of programming and mostly covered by the standard library already (or in case of jvm the java standard library) so I don’t think it would clear the minus 100 point rule which many people here in this forum and elsewhere have used to judge an addition to the language.

Also I don’t like the syntax. It’s confusing. Imagine you have no idea what it is and have to guess. I don’t think adding a new construct to the language that isn’t used often and then also unintuitive is a good idea.

5 Likes

Do you really has a lot of collection element swaps in your program? Maybe you are doing something wrong?

1 Like

Also why would obj[1 <- 2] be better than obj.swap(1, 2).
Your version isn’t even shorter, it’s less expressive and most people would have to look up what it does when they see it for the first time. obj.swap(1, 2) on the other hand is expressive, about the same length and does not require a new language construct.

2 Likes

Ok. It’s really bad idea :joy:

1 Like

The swap use case is one of possible use cases of destructuring assignment, which is not implemented at the moment. See discussion here: https://youtrack.jetbrains.com/issue/KT-11362#focus=streamItem-27-1846892.0-0