Okay, so I've been trying to learn Scala from a textbook, but it was written before Scala 3 was released so a lot of the example code doesn't compile.
Here's how the book introduces command line arguments:
println(args(0).toDouble+args(1).toDouble)
and my best attempt at converting this to something Scala 3 compatible:
@main def main(args: Array[String]) = {
println(args(0).toDouble+args(1).toDouble)
}
and here's what the compiler tells me:
[error] ./add.scala:1:1
[error] No given instance of type scala.util.CommandLineParser.FromString[Array[String]] was found for parameter fs of method parseArgument in object CommandLineParser
[error] @main def main(args: Array[String]) = {
[error] ^
How do I fix this? There's another question like this one already posted, but the answers seem to all be written in prior versions of Scala. As for the official release guide, it recommends using something to do with CLP, which I don't understand.
If you're using only Scala 3, the @main
annotation is the way to go but then the parameters should be defined as regular method parameters:
// ❌ Instead of:
@main def main(args: Array[String])
// ✅ Do:
@main def main(arg0: Double, arg1: Double)
One thing to note is that parameters can be typed, they don't have to be String
s only anymore. Conversion is handled for you automatically*.
You can thus write:
@main def main(arg0: Double, arg1: Double) = {
println(arg0 + arg1)
}
*: only simple types are supported by default, but this can be extended by providing instances of scala.util.CommandLineParser.FromString
. Note that this is the error you were initially getting: the compiler was saying "I don't know how to convert from String
to Array[String]
"
EDIT: as CoreyOConnor mentions in another answer, it's also possible to get all remaining parameters as a String*
(varargs) if you don't explicitly type some parameters.
If you're cross-compiling to Scala 2 or just you prefer the Scala 2 way, closer to Java's, then remove the @main
annotation and be sure to include the method in an object
.
object MyProgram {
def main(args: Array[String]) = ???
}
Documentation: https://docs.scala-lang.org/scala3/book/methods-main-methods.html