hello stupid question of the day about this code s...
# announcements
n
hello stupid question of the day about this code snippet:
while (shorteneds.putIfAbsent(url, this) != null) {}
of course, intellij complains that the block is empty any idea how to write a better version without the complaint? i’m probably missing something from stdlib...
d
Copy code
while (shorteneds.putIfAbsent(url, this) != null) {
  // intentionally empty
}
😅 1
j
Copy code
while (shorteneds.putIfAbsent(url, this) != null) Unit
👍 1
n
thanks @diesieben07 @Jurriaan Mous you were fast! i prefer the second better as it relies on types
d
The
Unit
is completely meaningless here, btw.
while (something) Int
does the same thing
n
yep but
Int
raises my eyebrow while with
Unit
i can understand the reason
n
Won’t the while busy-loop? It feels like there should be something in the body of the loop to wait for the existing entry to be removed
j
It should probably contain Thread.onSpinWait
And that better had be a synchronized collection or you might loop forever!
n
FYI it’s actually a hazelcast call and it should loop until it finds no collision
c
I might try below. even though it creates a longer code but I think it’s more readable.
Copy code
var result: Any?
do {
    result = shorteneds.putIfAbsent(url)
} while(result != null)

// or

var result = shorteneds.putIfAbsent(url)
while (result != null) {
    result = shorteneds.putIfAbsent(url)
}
because for me the while loop works like
while (condition) do {action}
. not
while(condition - and - action)
. If you know what I mean..