0

I want to use JCommander to parse args.

I wrote some code:

import com.beust.jcommander.{JCommander, Parameter}
import scala.collection.mutable.ArrayBuffer

object Config {
  @Parameter(names = Array("--categories"), required = true)
  var categories = new ArrayBuffer[String]
}

object Main {
  def main(args: Array[String]): Unit = {
    val cfg = Config
    JCommander
      .newBuilder()
      .addObject(cfg)
      .build()
      .parse(args.toArray: _*)
    println(cfg.categories)
  }
}

Howewer it fails with

com.beust.jcommander.ParameterException: Could not invoke null
    Reason: Can not set static scala.collection.mutable.ArrayBuffer field InterestRulesConfig$.categories to java.lang.String

What am i doing wrong?

Makar Nikitin
  • 319
  • 1
  • 13

2 Answers2

0

JCommander uses knowledge about types in Java to map values to parameters. But Java doesn't have a type scala.collection.mutable.ArrayBuffer. It has a type java.util.List. If you want to use JCommander you have to stick to Java's build-in types.

If you want to use Scala's types use one of Scala's libraries that handle in in more idiomatic manner: scopt or decline.

Mateusz Kubuszok
  • 24,995
  • 4
  • 42
  • 64
0

Working example

import java.util

import com.beust.jcommander.{JCommander, Parameter}

import scala.jdk.CollectionConverters._


object Config {
  @Parameter(names = Array("--categories"), required = true)
  var categories: java.util.List[Integer] = new util.ArrayList[Integer]()

}

object Hello {
  def main(args: Array[String]): Unit = {
    val cfg = Config
    JCommander
      .newBuilder()
      .addObject(cfg)
      .build()
      .parse(args.toArray: _*)
    println(cfg.categories)
    println(cfg.categories.getClass())
    val a = cfg.categories.asScala
    for (x <- a) {
      println(x.toInt)
      println(x.toInt.getClass())
    }
  }
}
Makar Nikitin
  • 319
  • 1
  • 13