Search code examples
javapicocli

Picocli, how to recognise presence of option with optional value and custom type converter


Picocli v2.3.0.

@CommandLine.Option(names = {"--number-headings"},
                    arity = "0..1",
                    paramLabel = "levels",
                    description = {"Adds numbers to headings. Optional parameter to set the heading levels to be numbered.",
                                   "eg. 2-4"})
public HeadingNumberingRange numberHeadings;

Custom type converter is registered and working correctly when a value is provided (mycommand --number-headings 2-5). But numberHeadings remains null if called like: mycommand --number-headings.

Example at http://picocli.info/man/2.x/#_optional_values suggests that a String typed option will receive an empty string when no value is provided.

So the empty string is the default value when option is present but no value is provided.

This allows us to distinguish between 3 situations:

  1. Option not present (we get null)
  2. Option present with no value (we get empty string)
  3. Option present with value (we get value)

With a custom ITypeConverter, the convert() method of the ITypeConverter is not called when there is no value provided. So what is the equivalent default value when option is present but no value is provided for custom types?


Solution

  • Thanks for raising this on the picocli issue tracker.

    As of picocli 3.0.0-alpha-5, custom type converters can map the empty String (when the option is present without a value) to a custom default value. This functionality is included in the picocli 3.0.0 GA release that just came out.