【问题标题】:Why in scala we need to define class structure to create new object of the same class为什么在scala中我们需要定义类结构来创建同一个类的新对象
【发布时间】:2017-09-12 10:01:07
【问题描述】:
class ReadHelper{}
object ReadHelper {}

class MainApp{
   val rHelp = ReadHelper//This line will be uneasy if I omit class declaration of ReadHelper
}

【问题讨论】:

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

标签: scala


【解决方案1】:

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

其实我们没有。

class ReadHelper{}

class MainApp{
  val rHelp: ReadHelper = new ReadHelper
}

请注意原来的情况

class ReadHelper {}
object ReadHelper {}

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

或者只是

object ReadHelper {}

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

rHelp 具有不同的类型。

object ReadHelper 不是class ReadHelper 的对象(在 OOP 语言中也称为 instance)。它就是班级的companion object。这是除类之外存在的类类结构(单例)。在字节码中你会发现两个类ReadHelper(类本身)和ReadHelper$(伴随对象)。

也许你应该 read more 了解 Scala 中的类、对象、伴生对象。

【讨论】:

    猜你喜欢
    • 2018-08-03
    • 2012-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多