如何使用运行时参数在 Scala 中创建单例对象

How to create a singleton object in Scala with runtime params

我正在尝试使用运行时指定的参数创建单例对象。 示例:

object NetworkPusher {
  val networkAdress = ???
  ...
 }

假设 networkAdress 参数来自命令行。我该如何解决这个问题?

使用lazy:

object Program {

  var networkAdress: String = _

  def main(args: Array[String]): Unit = {
    networkAdress = args(0)
    println(NetworkPusher.networkAdress)
  }

  object NetworkPusher {
    lazy val networkAdress = Program.networkAdress
  }
}

单例被延迟初始化。

scala> :pa
// Entering paste mode (ctrl-D to finish)

object Net {
  val address = Config.address
}
object Config { var address = 0L }

// Exiting paste mode, now interpreting.

defined object Net
defined object Config

scala> Config.address = "1234".toLong
Config.address: Long = 1234

scala> Net.address
res0: Long = 1234

FWIW.