Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass arguments to App object in Scala

Tags:

testing

scala

I am currently creating with scalatest.org some unit tests for my application:

scala> object Test extends App {
     | println(args)
     | }

How can I pass parameters to that object? I tried overriding the args value but after some research I discovered that it is not possible:

  /** The command line arguments passed to the application's `main` method.
   */
  @deprecatedOverriding("args should not be overridden", "2.11.0")
  protected def args: Array[String] = _args

  private var _args: Array[String] = _

How can I pass to the underscore _ custom parameters in the code?

Cheers

like image 976
zio Avatar asked Nov 04 '14 16:11

zio


People also ask

How do I pass an argument to a Scala object?

you can access your Scala command-line arguments using the args array, which is made available to you implicitly when you extend App . As an example, your code will look like this: object Foo extends App { if (args. length == 0) { println("dude, i need at least one parameter") } val filename = args(0) ... }

How do I pass parameters to a Scala script?

If bash is started with the -c option, then $0 is set to the first argument after the string to be executed, if one is present. Otherwise, it is set to the file name used to invoke bash, as given by argument zero. @ Expands to the positional parameters, starting from one.

How do I pass a command line argument in spark Scala?

Making this more systematic: Put the code below in a script (e.g. spark-script.sh ), and then you can simply use: ./spark-script.sh your_file. scala first_arg second_arg third_arg , and have an Array[String] called args with your arguments.

How do I run an object in Scala?

Step 1: Compile above file using scalac Hello. Scala after compilation it will generate a Geeks. class file and class file name is same as Object name(Here Object name is Geeks). Step 2: Now open the command with object name scala Geeks.


1 Answers

I think you want to invoke the main(args: Array[String]) method inherited from App.

scala> object Test extends App { args.foreach(println) }
defined object Test

scala> Test.main(Array("A1"))
A1

scala> Test.main(Array("A1", "A2"))
A1
A2
like image 85
Nate Avatar answered Sep 17 '22 13:09

Nate