Created
August 9, 2017 09:07
-
-
Save eygraber/345a422af1586b9385bfc421f70a8380 to your computer and use it in GitHub Desktop.
Delegate for flipping a boolean on access
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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