检查参数初始化的惯用方法

Idiomatic way to check for parameter initialization

我有一个必须在运行时初始化的变量 param

然后,我有一部分代码实现了以下内容:

if (param has been initialized)
     ...do something...
else
     print error and exit

在 Scala 中最惯用的方法是什么?

到目前为止,我是这样使用Option[X]的:

var param : Option[TheType] = None
...
val param_value : TheType = x getOrElse {println("Error"); null}

但是,因为我必须 return null 它看起来很脏。

我应该怎么做?

只需 mapforeach 即可:

param.foreach { param_value =>
  // Do everything you need to do with `param_value` here
} getOrElse sys.exit(3)  # Param was empty, kill the program

您还可以使用 for 理解风格:

for {
  param_value <- param
} yield yourOperation(param_value)

这样做的好处是,如果您的调用代码期望使用 param_value 作为来自 yourMethod 的 return 值执行某些操作,您将对 [=15= 的可能性进行编码] 在您的 return 类型中不存在(它将是 Option[TheType] 而不是潜在的 null TheType。)

我可能错了,但在我看来 Future 的使用适合你的问题:与其显式检查你需要的 param_value 是否已初始化,如果没有则完成程序,您可以让您的资源相关代码在资源正确初始化时执行:

val param: Future[TheType] = future {
      INITIALIZATION CODE HERE
}

param onFailure {
    case e => println("Error!");
}

param onSuccess {
    case param_value: TheType => {
        YOUR BUSINESS CODE HERE
    }
}