this post was submitted on 17 Nov 2024
142 points (93.8% liked)

Programmer Humor

32558 readers
463 users here now

Post funny things about programming here! (Or just rant about your favourite programming language.)

Rules:

founded 5 years ago
MODERATORS
 
you are viewing a single comment's thread
view the rest of the comments
[–] QuazarOmega@lemy.lol 13 points 5 days ago (2 children)

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

[–] Cube6392@beehaw.org 16 points 5 days ago (3 children)

been programming since 2008. the fuck is an elvis operator?

[–] dev_null@lemmy.ml 3 points 3 days ago* (last edited 3 days 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.

[–] jerkface@lemmy.ca 8 points 5 days ago

Been programming since the 80s, ditto.

[–] luciferofastora@lemmy.zip 4 points 5 days ago (1 children)
[–] Cube6392@beehaw.org 3 points 5 days ago (1 children)

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 8 points 5 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

[–] AVincentInSpace@pawb.social 3 points 4 days ago (2 children)

why would you call it anything other than the ternary operator

[–] dev_null@lemmy.ml 3 points 3 days ago* (last edited 3 days ago) (1 children)

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.

[–] AVincentInSpace@pawb.social 2 points 2 days ago (1 children)

The second one isn't valid syntax in any programming language I'm familiar with. What does it do?

[–] dev_null@lemmy.ml 4 points 2 days ago (1 children)

It's a shorthand for writing this:

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

This is equivalent:

variable = input ?: default
[–] AVincentInSpace@pawb.social 2 points 2 days ago* (last edited 2 days ago) (1 children)
[–] dev_null@lemmy.ml 2 points 2 days ago* (last edited 2 days ago)

It's in Kotlin and some other languages. C# has it but there it's actually A ?? B.

[–] QuazarOmega@lemy.lol 2 points 4 days ago

Read further down on my other comment to understand, it's just how the operator looks