https://kotlinlang.org logo
n

nfrankel

07/06/2020, 1:14 PM
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

diesieben07

07/06/2020, 1:16 PM
Copy code
while (shorteneds.putIfAbsent(url, this) != null) {
  // intentionally empty
}
😅 1
j

Jurriaan Mous

07/06/2020, 1:17 PM
Copy code
while (shorteneds.putIfAbsent(url, this) != null) Unit
👍 1
n

nfrankel

07/06/2020, 1:19 PM
thanks @diesieben07 @Jurriaan Mous you were fast! i prefer the second better as it relies on types
d

diesieben07

07/06/2020, 1:19 PM
The
Unit
is completely meaningless here, btw.
while (something) Int
does the same thing
n

nfrankel

07/06/2020, 1:28 PM
yep but
Int
raises my eyebrow while with
Unit
i can understand the reason
n

natpryce

07/06/2020, 1:38 PM
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

jw

07/06/2020, 1:54 PM
It should probably contain Thread.onSpinWait
And that better had be a synchronized collection or you might loop forever!
n

nfrankel

07/06/2020, 2:15 PM
FYI it’s actually a hazelcast call and it should loop until it finds no collision
c

Cheolho Jeon

07/06/2020, 2:31 PM
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..
3 Views