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

How to initialize a list / collection option from a set? #331

Closed
sschuberth opened this issue Jan 16, 2022 · 4 comments · Fixed by #332
Closed

How to initialize a list / collection option from a set? #331

sschuberth opened this issue Jan 16, 2022 · 4 comments · Fixed by #332

Comments

@sschuberth
Copy link
Contributor

sschuberth commented Jan 16, 2022

If in the following code PackageManager.ALL is a set:

private val packageManagers by option(
    "--package-managers", "-m",
    help = "The comma-separated package managers to activate, any of ${allPackageManagersByName.keys}."
).convert { name ->
    allPackageManagersByName[name]
        ?: throw BadParameterValue("Package managers must be one or more of ${allPackageManagersByName.keys}.")
}.split(",").default(PackageManager.ALL)

It does not compile as default() expects to get a list. I tried to play with unique(), but failed to find a syntax that compiles as wanted. In the end, I'd also like the packageManagers option to be a set.

Any hints?

@ajalt
Copy link
Owner

ajalt commented Jan 16, 2022

split turns the option value into a list, so default needs a list:

val packageManagers by option().enum<PackageManager>()
        .split(",")
        .default(listOf(PackageManager.ALL)) // or ALL.toList(), if all is already a collection
        .unique()

The type contraints on unique currently prevent it from being used this way, but they can be loosened to allow it.

fun <T, EachT, ValueT> OptionWithValues<List<T>, EachT, ValueT>.unique(): OptionWithValues<Set<T>, EachT, ValueT> {
    return copy(transformValue, transformEach, { transformAll(it).toSet() }, {})
}

@sschuberth
Copy link
Contributor Author

Thanks, I ended up using PackageManager.ALL.toList(). Not super nice, but I guess it's not worth to implement a splitTo() that would take a mutable set to solve this.

@ajalt
Copy link
Owner

ajalt commented Jan 16, 2022

You should also be able to do split(",").convert{it.toSet()}.default(ALL) if you prefer.

@sschuberth
Copy link
Contributor Author

No, thanks, I don't want to add another convert call. I just wanted to check that I'm not overlooking an existing elegant solution.

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

Successfully merging a pull request may close this issue.

2 participants