tags:

views:

676

answers:

5

Greetings,

I'm just going over some scala tutorials on the net and have noticed in some examples an object is declared at the start of the example.

Can anyone explain to me what the difference between class and object are as far as scala is concerned?

+2  A: 

An object has exactly one instance (you cannot not call new MyObject). You can have multiple instances from a class.

Object serves the same (and some additional) purposes as the static methods and fields in Java.

Thomas Jung
+5  A: 

You can think of the "object" keyword creating a Singleton object of a class, that is defined implicitely.

object A extends B with C

This will declare an anonymous class which extends B with the trait C and create a single instance of this class named A.

ziggystar
It will also define class A, and create all of the methods in object A as static methods on class A (for interfacing with Java). (Modulo a bug in Scala 2.7 that's been fixed in Scala 2.8)
Ken Bloom
A: 

I dont know exactly how scala defines it but in Object programming general a class is the definition and the object is the instance.

bang
Scala has a "object" keyword. This is different from other OO languages.
Thomas Jung
This is not an answer, but a question, no?
ziggystar
Not so different: objects created with the object keyword behave like usual object in any OO language.
Nicolas
But object != instance. This can get confusing.
Thomas Jung
The object keyword might be a little misleading if you're used to other OO languages. Have a look at http://stackoverflow.com/questions/609744/what-is-the-rationale-behind-having-companion-objects-in-scala for example.
André Laszlo
@ziggystar How is it a question ?!
bang
Still a class is a definition and an object is an instance (event if its a singelton).
bang
+6  A: 

A class is a definition, a description. It defines a type in terms of methods and composition of other types.

An object is a singleton -- an instance of a class which is guaranteed to be unique. For every object in the code, an anonymous class is created, which inherits from whatever classes you declared object to implement. This class cannot be seen from Scala source code -- though you can get at it through reflection.

There is a relationship between object and class. An object is said to the be companion-object of a class if they share the same name. When this happens, each has access to methods of private visibility in the other. These methods are not automatically imported, though. You either have to import them explicitly, or prefix them with the class/object name.

Daniel
A: 

An defining an object in Scala is like defining a class in Java that has only static methods. However, an in Scala an object can extend another superclass, implement interfaces, and be passed around as though it were an instance of a class. (So it's like the static methods on a class but better).

Ken Bloom