ProAndroidDev

The latest posts from Android Professionals and Google Developer Experts.

Follow publication

‘Extension classes’

Aidan Mcwilliams
ProAndroidDev
Published in
3 min readJul 16, 2020

--

sealed class Feature
object SomeFeature: Feature()
object SomeOtherFeature : Feature()
interface AppFeatures {
fun isEnabled(feature: Feature): Boolean
}
fun AppFeatures.isDisabled(feature: Feature): Boolean =
isEnabled(feature).not()
Yoda speech

Inline classes to the rescue!

inline class AppFeaturesExtension(val appFeatures: AppFeatures) {
val Feature.enabled: Boolean
get() = appFeatures.isEnabled(this)

val Feature.disabled: Boolean
get() = enabled.not()
}
AppFeaturesExtension(appFeatures).apply {
if (SomeFeature.disabled) {
TODO("do something when SomeFeature is disabled")
}
}
inline operator fun <T> AppFeatures.invoke(
appFeaturesExtensionContext: AppFeaturesExtension.() -> T
): T = appFeaturesExtensionContext(AppFeaturesExtension(this))
// calling appFeatures as if it were a function
// same as appFeatures.invoke, the invoke is implicit
appFeatures {
if (SomeFeature.disabled) {
TODO("do something when SomeFeature is disabled")
}
}

Takeaway

https://gist.github.com/Aidanvii7/14aeae7981759dbedab83e7f5ecabb32

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Published in ProAndroidDev

The latest posts from Android Professionals and Google Developer Experts.

No responses yet

Write a response