Question

How do I get this to work, I've tried with and without new keyword:

object Main extends App {
    override def main (args : Array[String] = new Array("default argument")) {
        println("args(0) = " + args(0))
    }
}

http://ideone.com/5AyTxy (I have tried other [1, 2] methods but I think that its val is causing issues)

Docs: http://docs.scala-lang.org/sips/completed/named-and-default-arguments.html#default_arguments

PS: I should confirm that I want this to be bound to the args name; rather than to another var or val. Additionally the scope needs to be global within main.

Was it helpful?

Solution 2

To satisfy your intent here (as clarified by your last comment to @AlexIv's answer) - keeping the field name of args while allowing for a default value for the field - you can override the field, using a reference to the original value prefixed by super.:

object Main extends App {
    override val args: Array[String] = if (super.args.isEmpty) Array("default argument") else super.args
    println("args(0) = " + args(0))
}

OTHER TIPS

Two notes:

1) When you extend App, the body of your object is your main function. "args" is a supplied value, you can just use it.

object MyApp extends App {
  println(args)
}

2) main will always be called with arguments. This makes sense, since otherwise Scala (and Java) would be inconsistent. The JVM doesn't test to see if you have any arguments before passing the arg list to your main function. If it did, it would call main(Array("args")) sometimes, and main() other times, which would create a problem!

A better way to do this would be to actually use args as it is:

object MyApp extends App {
  println(args.toList.headOption.getOrElse("Default first argument"))
}

If you want more than one argument though, you should check out a real argument parsing library, I recommend scopt.

You have to remove extends App and new:

object Main {
  def main (args : Array[String] = Array("default argument")) {
    println("args(0) = " + args(0))
  }
}

But this won't help you cause main is an entry point to your application and default Array will be overwritten by the system, for example:

object Main {
  def main (args : Array[String] = Array("default argument")) {
    println(args.isEmpty)
  }
}

Mac-mini:Desktop alex$ scalac main.scala
Mac-mini:Desktop alex$ scala Main
true
Mac-mini:Desktop alex$ scala Main hello
false

But if you need default Array, why not to make a new variable inside main?

object Main {
  def main (args : Array[String] = Array("default argument")) {
    val args = Array("default argument")
    println(args.isEmpty)
  }
}

or even shorter:

object Main extends App {
  val args = Array("default argument")
  println(args.isEmpty)
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top