簡體   English   中英

Scala:帶有參數的伴侶對象

[英]Scala: Companion object with arguments

我正在尋找一種使用arguments初始化companion對象的方法。 我嘗試過此操作,它有re-instantiation的風險。

private[mypackage] class A(in:Int) {
  def method = {}
}

object A {

  var singleton: Option[A] = None

  def getInstance(): A = {
    if(singleton.isDefined)
      singleton.get
    else {
        throw InitializationException("Object not configured")
      }
  }

  def getInstance(in:Int): A = {
    singleton = Some(new A(in))
    singleton.get
  }
}

有沒有更好的辦法?

純Scala方式

Scala允許您使用object關鍵字創建類型的單例對象。 Scala確保系統中僅A的一個實例可用。

private[myPackage] object A  {
  val configValue = Config.getInt("some_value")
  def fn: Unit = ()
}

對象的類型

scala> object A {}
defined object A

scala> :type A
A.type

有關Scala中的單例對象的更多信息Scala中的單例對象的說明

Guice注解

import com.google.inject.Singleton

@Singleton
class A (val value: Int) {
  def fn: Unit = ()
}

經典Java方式

使用synchronized關鍵字可以防止getInstance在調用時創建多個對象。 當然,該類的構造函數必須是private

您可以使用lazy val延遲創建單例,並將其基於在啟動過程中應更新一次的var

object A {
  // will be instantiated once, on first call
  lazy val singleton: A = create()

  private var input: Option[Int] = None

  // call this before first access to 'singleton':
  def set(i: Int): Unit = { input = Some(i) }

  private def create(): A = {
    input.map(i => new A(i))
      .getOrElse(throw new IllegalStateException("cannot access A before input is set"))
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM