I am trying to use the new immutable OptionParser in the Scala scopt 2.0.1 library. Since OptionParser takes a generic type and the help method already defines an action that returns Unit, I am getting a compile-time error:
case class Config(directory: String = null)
val parser = new OptionParser[Config]() {
def options = Seq(
opt("d", "directory", "directory containing the files to be processed") {
(value: String, config: Config) => config.copy(directory = value)
},
help("?", "help", "Show a usage message and exit"))
}
error: type mismatch;
[INFO] found : scopt.generic.FlagOptionDefinition[Nothing]
[INFO] required: scopt.generic.OptionDefinition[Config]
[INFO] Note: Nothing <: Config, but class OptionDefinition is invariant in type C.
How can I include a “help” option?
First of all, there seems to be an error in the library, where one of the overloaded methods of
opttakes a type parameterCwhich it shouldn’t — at least from what I can tell. It should just takeCfrom the class. Anyway, although you use that call, I guess Scala still correctly infers that thisCis the same as the class’sC(Config).The problem seems to be that
helpis completely useless — it gives youFlagOptionDefinition[Nothing]because itsaction: => Cimplementation is{this.showUsage; exit}.I think that the
OptionParserclass needs fixing…You could write your own
helpmethod that enforces theCtype parameter: