https://kotlinlang.org logo
#language-evolution
Title
# language-evolution
h

Hullaballoonatic

11/09/2019, 8:03 PM
so yeah, walrus operator?
Copy code
var next = stack.last
    get() {
        field = stack.pop()
        field
    }
Copy code
var next = stack.last
    get() = field := stack.pop()
k

karelpeeters

11/09/2019, 9:39 PM
They special cased
when
just to be able to avoid adding this operator 🙂
h

Hullaballoonatic

11/09/2019, 9:40 PM
Yeah, I'd like to know why they wanted to avoid it so badly yet added it to when
q

Quy D X Nguyen

11/09/2019, 9:46 PM
What the special case?
k

karelpeeters

11/09/2019, 9:47 PM
when(val x = foo())
is allowed
It's from the last update I think.
h

Hullaballoonatic

11/09/2019, 9:50 PM
Meanwhile you can't do
if (val x = foo())
like you can in Java.
e

elizarov

11/11/2019, 8:37 AM
But may I ask “why”? The example code you’ve given is a horrible anti-pattern — a property with a side effect 😱 Of course, there are some legitimate use-cases for “get and assign” operator. They are too infrequent to warrant a special operator, though. In cases where it is really needed you can do this (let’s name it properly in this example to highlight its side effect):
Copy code
fun moveNext() = stack.pop().also { next = it }
h

Hullaballoonatic

11/11/2019, 7:50 PM
don't iterators have side effects to
next
also? and, yeah, i used
also
in similar code i wrote. I wasn't really writing up this code as a good example of why it'd be nice to have, but instead just showcasing how it works. i think the better example of where they'd be applicable are in while and if statements:
Copy code
if ((val n = password.length) < 6) error("pw length of $n is too short. must be >= 6")
in that case, however, using kotlin's standard variable declaration syntax is the clear go-to
k

karelpeeters

11/11/2019, 8:58 PM
Iterator.next()
is a function.
4 Views