Any thoughts on this delegate (sync improvements, ...
# announcements
e
Any thoughts on this delegate (sync improvements, etc...)?
Copy code
class FlipOnAccess(
    private val initialValue: Boolean,
    private val onlyFirstAccess: Boolean = true
) : ReadOnlyProperty<Any, Boolean> {
  private val flipper = AtomicInteger(1)

  private val Int.isEven get() = and(1) == 0

  override fun getValue(thisRef: Any, property: KProperty<*>) =
      with(flipper.getAndIncrement()) {
        if (this == 1) {
          initialValue
        }
        else if (isEven || onlyFirstAccess) {
          !initialValue
        }
        else {
          initialValue
        }
      }
}
b
I’d probably rewrite that if-else chain as a
when()
. But that’s mostly just a style thing. I’d have to think through all the concurrency implications, but this seems pretty slick.