I was trying to create a case class in scala.
case class CaseClassPrimaryConstructor {
} //Error: 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 CaseClassPrimaryConstructor() {
} // Working fine
did not understand the behavior ? please help
It used to be allowed, but isn't anymore precisely for the reason mentioned in your last comment:
I was trying to create an instance like "caseObj:CaseClassPrimaryConstructor=CaseClassPrimaryConstructor" which is not valid saying "type mismatch; found : CaseClassPrimaryConstructor.type required: com.basic.constructor.CaseClassPrimaryConstructor"
CaseClassPrimaryConstructor
in an expression context (not after :
or in type parameter, or after new
) means the companion object of the CaseClassPrimaryConstructor
class, so you would still get the same error, which was rather confusing. For case classes, this companion object has apply
method with the same parameters as the primary constructor which just calls it. CaseClassPrimaryConstructor()
isn't really a special syntax for constructing case classes, it's syntax for calling the apply
method.
Also, instead of a case class without parameters you generally want an object
in the first place, since all instances will be equal, they shouldn't behave differently and so there is no need to create new instances at all.
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.