【问题标题】:How to pass arguments/parameters to a SCALA script如何将参数/参数传递给 SCALA 脚本
【发布时间】:2018-06-15 13:52:18
【问题描述】:

我们如何将参数传递给 scala 脚本,就像我们将参数传递给 shell 脚本一样。

【问题讨论】:

    标签: scala arguments


    【解决方案1】:

    像这样在顶部使用 bash 命令声明您的脚本

    Test.scala

    #!/bin/sh
    exec scala "$0" "$@"
    !#
    
    object Test {
      def main(args: Array[String]): Unit = {
        println(s"args: ${args.mkString("[", ", ", "]")}")
      }
    }
    

    有效

    [Desktop] ./Test.scala "scala is awesome" "java8 has lambdas"
    args: [scala is awesome, java8 has lambdas]
    

    更多关于$0$@的信息

    0  Expands to the name of the shell or shell script.
       This is set at shell initialization. If bash  is  
       invoked  with  a  file  of commands, $0 is set to 
       the name of that file.  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. When the expansion occurs within double quotes, each 
       parameter expands to a separate word. That is, "$@" is 
       equivalent to "$1", "$2" ... If the double-quoted 
       expansion occurs within a word, the expansion of the first
       parameter is joined with the beginning part of the original 
       word, and the expansion of the last parameter is joined
       with the last part of the original word. When there are no 
       positional parameters, "$@" and $@ expand to nothing 
       (i.e., they are removed).
    

    欲了解更多信息,请访问:Command line args for Scala scripts

    【讨论】:

    • 感谢您的快速回复,由于某种原因我无法得到。没关系。目前我正在研究 scala shell 意味着 scala>:load test.scala 那么如何在这里传递参数?抱歉,我是 scala 的新手
    • @KPM scala 脚本像 bash 脚本一样在命令行上运行。您不能加载到 repl 中。检查答案,我在命令行上使用了./Test.scala。无需将其加载到 repl 中
    • 我正在执行。斯卡拉。未找到。你能提示我吗?
    • @KPM 先从这里安装 scala scala-lang.org/download
    【解决方案2】:

    就像你必须设置一个环境变量来传递 JVM 参数一样,你可以为你的参数设置一个环境变量。

    set MYVARS=arg1 arg2 arg3

    然后在你的 scala 脚本中:

    val args = sys.env("MYVARS").split(" ").map(_.trim).toList
    args.foreach { println }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-18
      • 2011-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多