开发者

when to use singleton objects and when to use actual objects in scala

I would like to know if there is any specific rule or if there is a rule of thumb to be followed on using actual objects in scala vs singleton objects in scala

say i have a class lik开发者_开发问答e this

class GetDataInput {
 def getNameInput() {
 println("Enter the name value: ")
}
 def getTypeInput() {
   println("Enter the type value: ")
  }
 def getBothInput() {
   println("Enter the name value: ")
  println("Enter the type value: ")
 }
}

is it better to use it in regular terms like

val someval = new GetDataInput()
someval.getNameInput()

or is it good to create a singleton object for this class and access the methods using that

object GetDataInput {
  def getNameInp() = getNameInput()
}

Any pointers on this?


Generally you make an object when:

  • It makes absolutely no sense of having different instances of a potential class, for example, to enclose several pure functions (like methematical functions, factory methods)

  • You want to write the equivalent of java static method or static final constants. (see Companion objects).

  • You want a simpler alternative for enum values (a sealed trait extended by objectinstances).

In your example, all the functions are pure, and the class is stateless. Therefore all instances will be strictly equal. It makes sense to turn it into an object:

object GetDataInput {
  def getNameInput() {
    println("Enter the name value: ")
  }
  ...
}

If you made the wrong choice, don't worry, it is easy to refactor. Usually you can keep all existing calls to the object, simply by extracting the methods in a trait:

trait GetDataInput {
   def getNameInput() {
    println("Enter the name value: ")
  }
}

object GetDataInput extends GetDataInput //Bring all traits methods into the object
                                         // to keep previous behaviour

class MyGetDataInput( whatever: Foo ) extends GetDataInput {
   ...
}


The question is rather: "Do you need different instances of a type?" If so, then go for a class (or a trait), if not go for a singleton. And btw there are no specific guidelines for the language you are using only because it has the singleton pattern built into it.


In scala, one primary use of objects is to fill the role of singletons. If you want to use a class as a singleton, just declare the class itself as an object. Then you could do:

GetDataInput.getNameInput()

Internally, scala will lazily create a single instance of your class and keep it alive for the duration of the program, so anytime you call a method on the object, you're really calling methods of a singleton instance of the class managed by the scala runtime.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜