-1
class ReadHelper{}
object ReadHelper {}

class MainApp{
   val rHelp = ReadHelper//This line will be uneasy if I omit class declaration of ReadHelper
}
Mirza Obaid
  • 1,707
  • 3
  • 23
  • 35
  • What's the error you get then? It works just fine for me. – michaJlS Sep 12 '17 at 10:07
  • Because this is the purpose of writing classes. If you have a Java-background, you could imagine the object definition as the place for all static methods in the class, the class definition the place for the other stuff. You could delete both, if you don't need one of them. – Thomas Böhm Sep 12 '17 at 10:09
  • I am getting error as "not found: type ReadHelper" –  Sep 12 '17 at 10:17
  • 2
    @Dnyaneshwar are you sure? This error occures when i remove `object Readhelper {}`, not the class? – Thomas Böhm Sep 12 '17 at 10:25

1 Answers1

4

Why in scala we need to define class structure to create new object of the same class?

Actually we don't.

class ReadHelper{}

class MainApp{
  val rHelp: ReadHelper = new ReadHelper
}

Please pay attention that in the original case

class ReadHelper {}
object ReadHelper {}

class MainApp{
  val rHelp: ReadHelper.type = ReadHelper
}

or just

object ReadHelper {}

class MainApp{
  val rHelp: ReadHelper.type = ReadHelper
}

rHelp has a different type.

object ReadHelper is not an object (aka instance in OOP-languages) of class ReadHelper. It's so called companion object of the class. This is a class-like structure (a singleton) existing besides the class. In byte code you will find two classes ReadHelper (the class itself) and ReadHelper$ (companion object).

Maybe you should read more about classes, objects, companion objects in Scala.

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66