特质作为辛格尔顿

wip*_*man 1 singleton scala traits

有可能trait成为一个singleton吗?

我要实现的目标是拥有一个干净轻巧的API,可以将其扩展到整个应用程序,如下所示:

trait SingletonTrait {
  // element I wish to be unique throughout my application
  val singletonElement = ///

  ...
}

// uses *singletonElement*
object MainApplication extends SingletonTrait {
  ...
}

// uses *singletonElement*
class SomeClass(...) extends SingletonTrait {
  ...
}
Run Code Online (Sandbox Code Playgroud)

In the same idea implied by a getOrCreate() function that would retrieve an existing instance of an element if one already exists or creates it otherwise.

Krz*_*sik 5

Maybe just create value in companion object and reference it in trait?

trait SingletonTrait {
  final lazy val singletonElement = SingletonTrait.SingletonElement
}

object SingletonTrait {
  lazy val SingletonElement = {
    println("Creating singleton element!")
    "singleton element"
  }
}

// uses *singletonElement*
class SomeClass() extends SingletonTrait {
    println(s"Using ${singletonElement} in class.")
}

new SomeClass()
new SomeClass()
new SomeClass()
Run Code Online (Sandbox Code Playgroud)

It prints:

Creating singleton element!
Using singleton element in class.
Using singleton element in class.
Using singleton element in class.
Run Code Online (Sandbox Code Playgroud)