How to create a singleton object in Scala with runtime params

前端 未结 2 1557
别那么骄傲
别那么骄傲 2021-01-18 11:30

I\'m trying to create a singleton object with parameters which are specified by runtime. Example:

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


        
相关标签:
2条回答
  • 2021-01-18 11:34

    Using 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
      }
    }
    
    0 讨论(0)
  • 2021-01-18 11:54

    Singletons are initialized lazily.

    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.

    0 讨论(0)
提交回复
热议问题