Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Expose Feature.defaultOption "statically" through companion object #305

Closed
AlexKrupa opened this issue Apr 14, 2023 · 2 comments
Closed

Comments

@AlexKrupa
Copy link
Contributor

AlexKrupa commented Apr 14, 2023

Currently to access a feature's default option you need one of its existing options, e.g.

AuthType.Retina.defaultOption

where the Retina part is only misleading because it's irrelevant — defaultOption could return AuthType.Fingerprint.

I'd prefer to access it "statically" to avoid hardcoding the irrelevant option e.g.

AuthType.defaultOption

There is a workaround, but it has the disadvantage of being a top-level function instead of being accessible through a feature:

inline fun <reified T> defaultOption(): T where T : Feature<T>, T : Enum<T> =
  enumValues<T>().first().defaultOption

val default = defaultOption<AuthType>()

Any design considerations I could be missing here?

@AlexKrupa AlexKrupa changed the title Expose Feature.defaultOption through its companion object Expose Feature.defaultOption "statically" through companion object Apr 14, 2023
@MiSikora
Copy link
Owner

MiSikora commented Apr 19, 2023

There is no way to require it in a contract. Classes cannot be forced to have a companion object, so it cannot be provided in the base library. This could only be done via code generation as a "bonus". But I wouldn't want to have it in the core generator engine. I could imagine a feature for others to hook into generation process to modify the output as they wish. But ATM this seems like an overkill for this simple feature request.

There is an extension on Class<Feature<T>>, which allows you to use it like this YourFeature::class.java.defaultOption. You can shorten it to KClass with an extension wrapper.

public val <T : Feature<out T>> KClass<out T>.defaultOption: T
    get() = java.defaultOption

@AlexKrupa
Copy link
Contributor Author

Sounds reasonable, thanks. I guess this idea could be revisited after statics.


The top-level function actually turned out just fine for us — most often type inference makes it simpler than a namespaced alternative.

class State(val authType: AuthType)

val initialState = State(authType = defaultOption())

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants