Skip to content

Instantly share code, notes, and snippets.

@eygraber
Created August 9, 2017 09:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eygraber/345a422af1586b9385bfc421f70a8380 to your computer and use it in GitHub Desktop.
Save eygraber/345a422af1586b9385bfc421f70a8380 to your computer and use it in GitHub Desktop.
Delegate for flipping a boolean on access
class FlipOnAccess(
private val initialValue: Boolean = false,
private val onlyFirstAccess: Boolean = false
) : 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()) {
when {
this == 1 -> initialValue
isEven || onlyFirstAccess -> !initialValue
else -> initialValue
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment