-2

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.

1
  • 8
    I think you're confusing the object concept with the object keyword. Commented Mar 30, 2017 at 5:19

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

the object keyword must be lowercase in your example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.