Created
July 17, 2020 08:00
-
-
Save Aidanvii7/14aeae7981759dbedab83e7f5ecabb32 to your computer and use it in GitHub Desktop.
Companion code for https://medium.com/@aidan.vii/extension-classes-f9dcf5878b71
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
fun main() { | |
FakeAppFeatures { | |
if (SomeFeature.enabled) { | |
println("some feature is enabled!") | |
} | |
} | |
} | |
sealed class Feature | |
object SomeFeature : Feature() | |
interface AppFeatures { | |
fun isEnabled(feature: Feature): Boolean | |
} | |
object FakeAppFeatures : AppFeatures { | |
override fun isEnabled(feature: Feature): Boolean = true | |
} | |
inline class AppFeaturesExtension(val appFeatures: AppFeatures) { | |
val Feature.enabled: Boolean | |
get() = appFeatures.isEnabled(this) | |
val Feature.disabled: Boolean | |
get() = enabled.not() | |
} | |
inline operator fun <T> AppFeatures.invoke( | |
appFeaturesExtensionContext: AppFeaturesExtension.() -> T | |
): T = appFeaturesExtensionContext(AppFeaturesExtension(this)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment