简体   繁体   English

Scala / IntelliJ:案例对象X与案例类X与案例类X()

[英]Scala/IntelliJ: case object X vs case class X vs case class X()

There are case classes in Scala: Scala中有案例类:

case class X(one: One, two: two)

There are case objects which have only one instance (which makes sense): 有些案例对象只有一个实例(这很有意义):

case object X

When I declare a case class without parameters, IntelliJ does the right thing and deprecation-warns me to make it a case object: 当我声明不带参数的case类时,IntelliJ做正确的事并弃用警告我使其成为case对象:

case class X // deprecated stuff

However it does not warn me about 但是它并没有警告我

case class X()

Which makes me wonder whether there is a difference between case class X and case class X() ? 这使我想知道case class Xcase class X()之间是否有区别?

I don't know what Scala version you are using, but in 2.11 this is not only deprecated but indeed an error: 我不知道您使用的是什么Scala版本,但是在2.11中,这不仅被弃用,而且确实是一个错误:

 Error:(34, 17) case classes without a parameter list are not allowed;
 use either case objects or case classes with an explicit `()' 
 as a parameter list.
   case class Foo
                 ^

Simply, you cannot pattern match against a no-parameter-list case class, so there is no use for them. 简而言之,您无法针对无参数列表案例类进行模式匹配,因此它们没有用。

case class Foo()

def test(in: Any) = in match {
  case Foo() => "foo"
  case _     => "other"
}

When you declare a case object, only a single instance is ever created. 声明案例对象时,只会创建一个实例。 However, you can have multiple different instances of a no-param case class. 但是,无参数案例类可以有多个不同的实例。 Why you might want that is a different matter. 为什么您会想要那是另一回事。

In principle, there is no difference between case class Foo and case class Foo() . 原则上, case class Foocase class Foo()之间没有区别。 I think the former was deprecated because of how easy it is to inadvertently misuse it. 我认为前者已被弃用,因为不经意间滥用它很容易。 This post illustrates the point nicely. 这篇文章很好地说明了这一点。

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

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