gpt4 book ai didi

scala - 在 Scala 脚本中使用命令行参数的惯用方法

转载 作者:行者123 更新时间:2023-12-03 09:12:52 25 4
gpt4 key购买 nike

我想创建一个通用的 Scala 脚本模板(使用 Conscript)。该脚本应采用命令行选项,例如用于启用详细模式的标志“-v”。

在 Perl 脚本中,我将创建一个全局变量 $verbose,根据标志是否存在,我将其设置为 true 或 false(或者更确切地说 1 或 0)。据我了解,在脚本中设置全局变量不是 Scala 方式。

考虑以下示例:

object Main {
def main(args: Array[String]) {
val options = parseOptions(args); // some way of parsing

// how to use 'options' in the remainder of the script?
}
}

怎么做呢?我看到的一种方法是将选项值保留为闭包中的上下文变量,即从嵌套函数访问它们。但是,使用嵌套函数的问题是我无法为它们编写单元测试。另一种简单的方法是在每次函数调用时传递选项,但这似乎很笨拙。

有什么建议吗?

最佳答案

对于解析选项,您可以使用 https://github.com/scopt/scopt ,但我发现您实际上是在询问如何使用选项解析器可能返回的 Config 对象。

我认为你需要传递 Config 对象;它是使用它的代码的依赖项,并且代码应该尽可能直接提供其依赖项,而不是通过全局变量,正如您所注意到的。

如果您想节省一些输入,您可以隐式传递,即

case class Config(verbose: Boolean)

object Main {
def main(args: Array[String]) {
implicit val config: Config = parseOptions(args); // some way of parsing

new FooComponent().doSomeStuff()
}
}

class FooComponent()(implicit config: Config) {

def doSomeStuff() {
... stuff
if (config.verbose) {
println(...)
}
...
}
}

您还可以使用 IoC 模式,以便单独的模块不依赖于 Main.Config,而是公开一个接口(interface),声明它们需要 Config 将实现的配置。

case class Config(verbose: Boolean) extends FooHandler.Config {
def printFooInfo: Boolean = verbose
}

object Main {
def main(args: Array[String]) {
val config: Config = parseOptions(args); // some way of parsing

FooHandler.handleFoo(config)
}
}

// This looks contrived with small code, but works well if
// your codebase is large and FooHandler is far away from Main
object FooHandler {
trait Config {
def printFooInfo: Boolean
}

def handleFoo(config: Config) {
... stuff
if (config.printFooInfo) {
println(...)
}
...
}
}

关于scala - 在 Scala 脚本中使用命令行参数的惯用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40305024/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com