Search code examples
parsingscalaapache-commons-cli

Scala error compiling OptionBuilder


I am using Apache commons cli (1.2) for command line parsing.

I have the following in my code:

import org.apache.commons.cli.OptionBuilder
OptionBuilder.withLongOpt("db-host").hasArg.
withDescription("Name of the database host").create('h')

I get the error hasArg is not a member of org.apache.commons.cli.OptionBuilder. It makes no difference if I change .hasArg to .hasArg().

Why?

BTW, Java parses this fine.


Solution

  • import org.apache.commons.cli.OptionBuilder
    OptionBuilder.withLongOpt("db-host").hasArg.
    withDescription("Name of the database host").create('h')
    

    I get the error hasArg is not a member of org.apache.commons.cli.OptionBuilder. It makes no difference if I change .hasArg to .hasArg().

    Why?

    Because there is no instance method hasArg in OptionBuilder, only a static method. Since hasArg is a static method, you obviously need to call it on the class, not on an instance of the class.

    BTW, Java parses this fine.

    I don't understand what this has to do with parsing. Scala parses this just fine, too. Plus, what some completely different programming does or doesn't do with this code is utterly irrelevant, since this is Scala code, not some other language.

    You need to do something like this:

    import org.apache.commons.cli.OptionBuilder
    
    OptionBuilder.withLongOpt("db-host")
    OptionBuilder.hasArg
    OptionBuilder.withDescription("Name of the database host")
    
    val optionParser = OptionBuilder.create('h')