1

Someone asked me: Why scala provides object keyword?

I answer that with object we can:

  1. create single instance on the language level
  2. create new instance of other types as factories
  3. combine different traits

But he said "These are what object can do, but not why".

What should I answer this question?

(I just read some articles about object, can I answer: Because scala want to support module on language level? )

Freewind
  • 193,756
  • 157
  • 432
  • 708

1 Answers1

1

object is there to avoid static members. Scala was designed as a pure object oriented language, and static just isn't object oriented. static also makes code harder to understand as you mix code that just doesn't belong together conceptually. In general, separating static and instance members is a good idea.

Also object reduces boilerplate by implementing the singleton pattern for you and makes useless types less present.

Just compare:

class SomeGlobalService {
   private SomeGlobalService instance = null

   private SomeGlobalService() {
     <constructor code>
   }

   public static SomeGlobalService getInstance() {
     if (instance == null) 
       instance = new SomeGlobalService
     return instance
   }

   <members>
}

SomeGlobalService.getInstance().<someMember>

To

object SomeGlobalService {
  <constructor code>
  <members>
}

SomeGlobalService.<someMember>

In the first example the package is polluted by the useless class SomeGlobalService which you most defenetely will never use directly. In scala the type is less visible as it is SomeGlobalService.type.

Martin Ring
  • 5,404
  • 24
  • 47
  • Isn't a static variable no object? – bebo Jun 20 '14 at 15:15
  • a static constant is indeed an object, but it is at the wrong place. why would you put a static constant pointing to an instance of a class into the definition of a class? that is like spreading a bowl of potato salad on a recipe for potato salad. it does not belong together conceptually! – Martin Ring Jun 20 '14 at 15:46