Default arguments to Scala's main function?

断了今生、忘了曾经 提交于 2019-12-12 15:41:46

问题


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.


回答1:


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))
}



回答2:


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.




回答3:


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)
}


来源:https://stackoverflow.com/questions/19217564/default-arguments-to-scalas-main-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!