Factory object and class case

I want to create a factory object with the given method method, which would create the base case class - here is an example code

object DeptEntry { def apply(url: String, fullName: String, address: String, city: String): DeptEntry = { new DeptEntry(url.toLowerCase, fullName.toLowerCase, address.toLowerCase, city.toLowerCase) } } case class DeptEntry private(url: String, fullName: String, address: String, city: String) { } 

The problem is that the apply method in the constructor of the object class and case have the same list of parameters. Therefore, the compiler gives me this error:

 method apply is defined twice conflicting symbols both originated in file 'DeptEntry.scala' case class DeptEntry private(url: String, fullName: String, ^ 

Is there any solution to this problem?

thanks a lot

+4
source share
4 answers

One possibility is to hide (a little) the class from your users:

 sealed trait DeptEntry object DeptEntry { def apply(url: String, fullName: String, address: String, city: String): DeptEntry = // ... case class Value protected[DeptEntry]( url: String, fullName: String, address: String, city: String ) } 

Thus, the conflict does not exist, and you can still match pattern matching on DeptEntry.Value if necessary. It depends on your use case if this solution is convenient or not. If you want this attribute to have the correct val s, you can declare it as

 sealed trait DeptEntry { val url: String val fullName: String val address: String val city: String } 

and the fields in the case class will override them.

0
source

Declare a case abstract class

 object DeptEntry { def apply(url: String, fullName: String, address: String, city: String): DeptEntry = { new DeptEntry(url.toLowerCase, fullName.toLowerCase, address.toLowerCase, city.toLowerCase) {} } } abstract case class DeptEntry private(url: String, fullName: String, address: String, city: String) { } 

This according to Iulian Dragos comments SI-844

+3
source

You can make DeptEntry a โ€œnormalโ€ (not cool) class. Or you can use a method with a different name in the object. (e.g. DeptEntry.lowerCase (...))

0
source

When creating a case class , the Scala compiler automatically creates a companion object using the apply method for you. This method is used with the same parameters as the constructor of the case class. This is why you get this compiler error. The fact that you cannot overwrite it ensures that it will look like this:

 val inputUrl = "MyUrl://blabla" val DeptEntry(outputUrl, _, _, _) = DeptEntry(inputUrl, "", "", "") outputUrl == inputUrl 

Try removing case from the class definition and write the companion apply object yourself (and unapply if you need to extract) (and toString , equals and hashCode in the class itself, if necessary).

0
source

Source: https://habr.com/ru/post/1489658/


All Articles