简体   繁体   中英

Scala/IntelliJ: case object X vs case class X vs case class X()

There are case classes in 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 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() ?

I don't know what Scala version you are using, but in 2.11 this is not only deprecated but indeed an error:

 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() . I think the former was deprecated because of how easy it is to inadvertently misuse it. This post illustrates the point nicely.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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