Main arguments question

I found this doesn’t work:

def main(args:Array[Int]) = { .. }

but should force into:

def main(args:Array[String]) = { .. }

So we can’t pass an Int type as the command line argument?

I think C is possible to pass an int type:

int main(int argc, char **argv) { /* ... */ }

Thank you.

You can use Int* instead of Array[Int]. This is Scala 3:

// in file script.scala
@main def hello(args: Int*): Unit = args foreach println

I can run it like this:

$ scala script.scala 1 2 3
1 Like

In Scala 2, you can convert the String arguments to integers using .toInt. They must be “integer strings” of course, e.g., “2”, “4”, etc.


I think C is possible to pass an int type

I think you may have misunderstood the signature of main in C. argc is the number of arguments — the equivalent of args.length in Java/Scala. The combination of int argc and char **argv is effectively the same as the JVM’s Array[String], since on the JVM an array knows its own size.


If you aren’t on Scala 3, you could get something similar to the Scala 3 feature that @spamegg1 mentioned using a library such as GitHub - com-lihaoyi/mainargs: A small, convenient, dependency-free library for command-line argument parsing in Scala

But for simple use cases (little scripts and such) I would normally just follow Russ’s suggestion. I’ll add that Scala 2.13’s toIntOption is useful if you aren’t sure if a string is parseable to an integer or not.

1 Like