I have started learning Scala.Is there any difference between an object in Java versus an object in Scala. As per my understanding the object created in Scala is singleton. Any other pointers please.
-
8I think you're confusing the object concept with the [`object` keyword](http://stackoverflow.com/a/1755521/1553851). – shmosel Mar 30 '17 at 05:19
2 Answers
In Java, Object
(upper case) is the top class. All classes extend Object
. Primitive types (int
, long
, etc) don't extend Object
because they are not a class
In Scala, there's a a different hierarchy. Everything extends class Any
: reference types extend AnyRef
, and value types extend AnyVal
, unlike Java, there are no primitives. (check docs: http://docs.scala-lang.org/tutorials/tour/unified-types)
But the object
you are referring in Scala is a singleton yes. It's very common to have a class that you want to be a singleton. In java there's a pattern to achieve that (for instance http://www.javaworld.com/article/2073352/core-java/simply-singleton.html), in scala they created the object
keyword as a shorthand.
there is also a special case: when there's a class
and an object
with the same name defined in the same compilation unit, the object is called a companion object, and basically you can think of it as holding the static methods you would have in Java
More on the subject at http://docs.scala-lang.org/tutorials/tour/singleton-objects.html

- 363,080
- 75
- 446
- 653

- 7,635
- 9
- 44
- 82
It depends on how you are creating an object in Scala. It's not like all object creation is Singleton.
For example:
object Shiva { /*some code*/}
Will create a singleton object. But if you define a class like you do in Java, you can create multiple instances.

- 28,161
- 11
- 65
- 105