模式匹配args并在轻量级Scala脚本中提供错误消息

Ste*_*eve 5 error-handling scripting scala pattern-matching

我写了一些简单的scala脚本,最后以简单的模式匹配开头,args如:

val Array(path, foo, whatever) = args
// .. rest of the script uses "path", "foo", etc.
Run Code Online (Sandbox Code Playgroud)

当然,如果我提供了错误数量的参数,我会得到一个难以理解的错误:

scala.MatchError: [Ljava.lang.String;@7786df0f
    at Main$$anon$1.<init>(FollowUsers.scala:5)
    ...
Run Code Online (Sandbox Code Playgroud)

是否有一种简单的方法可以提供更有用的错误消息?我目前的解决方法是执行以下操作:

args match {
  case Array(path, foo, whatever) => someFunction(path, foo, whatever)
  case _ => System.err.println("usage: path foo whatever")
}
def someFunction(path: String, foo: String, whatever: String) = {
  // .. rest of the script uses "path", "foo", etc.
}
Run Code Online (Sandbox Code Playgroud)

但是,由于必须定义一个完整的其他功能,并且必须在很多地方重复"路径","foo"和"无论什么",这感觉就像很多样板.有没有更好的办法?我想我可能会丢失函数并将正文放入匹配语句中,但这对我来说似乎不太可读.

我知道我可以使用众多命令行参数解析包中的一个,但我真的在寻找一些非常轻量级的东西,我不需要添加依赖项并修改我的类路径.

huy*_*hjl 3

怎么样?

val Array(path, foo, whatever) = if (args.length == 3) args 
  else throw new Exception("usage:path foo whatever")
Run Code Online (Sandbox Code Playgroud)

==编辑==

基于兰德尔的评论:

require(args.length == 3, "usage: path foo whatever")
val Array(path, foo, whatever) = args
Run Code Online (Sandbox Code Playgroud)

这是最小的样板。您的 vals 在范围内,您不必处理右大括号,并且您会收到使用错误消息。