为什么在scala中我们需要定义类结构来创建同一类的新对象

为什么在scala中我们需要定义类结构来创建同一类的新对象,scala,Scala,为什么在scala中我们需要定义类结构来创建新的 同一班 实际上我们没有 class ReadHelper{} object ReadHelper {} class MainApp{ val rHelp = ReadHelper//This line will be uneasy if I omit class declaration of ReadHelper } 请注意,在原来的情况下 class ReadHelper{} class MainApp{ val rHelp:

为什么在scala中我们需要定义类结构来创建新的 同一班

实际上我们没有

class ReadHelper{}
object ReadHelper {}

class MainApp{
   val rHelp = ReadHelper//This line will be uneasy if I omit class declaration of ReadHelper
}
请注意,在原来的情况下

class ReadHelper{}

class MainApp{
  val rHelp: ReadHelper = new ReadHelper
}
或者只是

class ReadHelper {}
object ReadHelper {}

class MainApp{
  val rHelp: ReadHelper.type = ReadHelper
}
rHelp
具有不同的类型

对象ReadHelper
不是
类ReadHelper
的对象(在OOP语言中称为实例)。这就是所谓的全班同学。这是存在于类之外的类状结构(单例)。在字节码中,您将发现两个类
ReadHelper
(类本身)和
ReadHelper$
(伴生对象)


也许您应该了解Scala中的类、对象和伴生对象。

那么您会遇到什么错误?这对我来说很好,因为这是写作课的目的。如果您有Java背景,您可以想象对象定义是类中所有静态方法的位置,类定义是其他内容的位置。如果您不需要其中一个,您可以同时删除它们。我收到的错误为“未找到:键入ReadHelper”@Dnyaneshwar您确定吗?当我删除
对象Readhelper{}
而不是类时,会发生此错误吗?
object ReadHelper {}

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