Kogesho Kogesho - 3 months ago 12
Scala Question

Main(args) to include multiple arrays

I have two projects: one is Java and one is Scala. The Java project has to pass some parameters to the Scala project, via

main(args)
.

def main(args: Array[String])


It needs to pass some variable names (such as database and a MongoDB collection name), but it also needs to pass two arrays that have variable length. An example would be:

(dbName, collectionName, numberOfClusters,
category1, category2,..., categoryN,
column1, column2, ..., columnN)


I am not sure how to parse this kind of input. The only thing that comes to my mind is calculating the number of elements in each array and inserting that number as a parameter so that when it is read, the indexes and offsets can be calculated to know where each array starts. I can access the individual elements from this args, by using:

args.apply(i)


which returns the element at
i
'th index. But I don't know where the values for the first array (category) end and where the values for second array (column) start. I am looking for the industry standard solution for parsing args of main that include more than one unknown sized arrays.

Answer

There are a number of unclear issues with your question, but why can you not pass your arrays as arrays? Specifically, as comma-delimited arrays that can easily be parsed into a Scala List?

object MainExp {
  def main(args: Array[String]): Unit = {
    if (args.length != 5) {
      println("Invalid number of arguments!")
    } else {
      val dbName = args(0)
      val collectionName = args(1)
      val numberOfClusters = args(2)
      val categories = args(3).split(',').toList
      val columns = args(4).split(',').toList
      println("Database=%s\nCollection=%s\nClusters=%s\n".format(dbName, collectionName, numberOfClusters))
      println("Categories: length=%s".format(categories.length))
      categories.foreach(x => println("\t%s".format(x)))
      println("Columns: length=%s".format(columns.length))
      columns.foreach(x => println("\t%s".format(x)))
    }
  }
}

The above yields:

$ scala MainExp.scala myDB aCollection 42 red,blue,green alpha,gamma,delta,omega
Database=myDB
Collection=aCollection
Clusters=42

Categories: length=3
    red
    blue
    green
Columns: length=4
    alpha
    gamma
    delta
    omega

In this fashion an arbitrary program can call into your Scala script. Every time there will only be five arguments.

(Note that I'm not sure your approach of calling a whole separate execution context is the correct one, given that both your programs are on the JVM, but this should answer the asked question of how to convert command line arguments into knowable-length lists.)