Hullaballoonatic

    Hullaballoonatic

    2 years ago
    so yeah, walrus operator?
    var next = stack.last
        get() {
            field = stack.pop()
            field
        }
    var next = stack.last
        get() = field := stack.pop()
    karelpeeters

    karelpeeters

    2 years ago
    They special cased
    when
    just to be able to avoid adding this operator 🙂
    Hullaballoonatic

    Hullaballoonatic

    2 years ago
    Yeah, I'd like to know why they wanted to avoid it so badly yet added it to when
    q

    Quy D X Nguyen

    2 years ago
    What the special case?
    karelpeeters

    karelpeeters

    2 years ago
    when(val x = foo())
    is allowed
    It's from the last update I think.
    Hullaballoonatic

    Hullaballoonatic

    2 years ago
    Meanwhile you can't do
    if (val x = foo())
    like you can in Java.
    elizarov

    elizarov

    2 years ago
    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):
    fun moveNext() = stack.pop().also { next = it }
    Hullaballoonatic

    Hullaballoonatic

    2 years ago
    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:
    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
    karelpeeters

    karelpeeters

    2 years ago
    Iterator.next()
    is a function.