简体   繁体   English

Scala:它是一个类实例吗?

[英]Scala: Is it a class instance?

If I run this code (see it below) I get CaseClass as printed message. 如果我运行此代码(见下文),我将CaseClass作为打印消息。

case class CaseClass(var name: String)

object Main extends App {
  val obj = CaseClass
  println(obj)
}

But what does it mean? 但是这是什么意思? I mean is CaseClass similar to Java's CaseClass.class ? 我的意思是CaseClass类似于Java的CaseClass.class

When you define a case class it actually defines both a class AND an object , both with the same name. 定义case class它实际上定义了一个class和一个object ,它们都具有相同的名称。 When you say val obj = CaseClass , you are actually assigning the object , a singleton object, to obj . 当你说val obj = CaseClass ,你实际上是将object ,一个单例对象分配给obj

It's kind of like: 它有点像:

class NonCaseClass(var name: String) {  // the actual class
  override def toString = "the class version" 
}
object NonCaseClass {                   // singleton companion object
  override def toString = "the object version" 
}

val obj = NonCaseClass   // this assigns the companion object to a variable
println(obj)
// the object version

This is different from instantiating an instance of the class CaseClass : 这与实例化CaseClass类的实例不同:

val obj2 = new NonCaseClass("x")
println(obj2)
// the class version

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM