• QuazarOmega@lemy.lol
    link
    fedilink
    arrow-up
    12
    ·
    3 days ago

    On the left you have Elvis Presley, while on the right there’s the so-called Elvis operator

      • dev_null@lemmy.ml
        link
        fedilink
        arrow-up
        1
        ·
        edit-2
        4 hours ago

        Because it’s not one. Ternary operator is A ? B : C, Elvis operator is A ?: B. The same two characters are involved, but both the syntax and effect is different.

      • dev_null@lemmy.ml
        link
        fedilink
        arrow-up
        2
        ·
        edit-2
        4 hours ago

        It’s a shorthand for writing this:

        variable = if (input != null) input else default
        

        This is equivalent:

        variable = input ?: default
        

        The answers confusing it with the ternary operator are wrong.

        • The Cuuuuube@beehaw.org
          link
          fedilink
          English
          arrow-up
          4
          ·
          2 days ago

          gotacha. i’ve only ever heard them called ternaries. maybe i’m old. maybe i’m too young. definitely one of the two

          • QuazarOmega@lemy.lol
            link
            fedilink
            arrow-up
            7
            ·
            2 days ago

            It specifically refers to this shorthand ?: that works like this:

            $value = $thing_that_could_be_truthy ?: 'fallback value';
            
            # same as
            
            $value = $thing_that_could_be_truthy ? $thing_that_could_be_truthy : 'fallback value';
            

            The condition is also the value if it is truthy