0
votes

I have a case class

case class SiteID(channel: String, locale: String)

Locale can be "en-GB" or "en_GB" . So I want to replace the hyphen by underscore.

The idea is to transform , so there is this equality

SiteID("blabla","en-GB") == SiteID("blabla","en_GB")

I tried with the following code

case class SiteID(channel: String, locale: String)

object SiteID{

  def apply(channel: String, locale: String):SiteID =  SiteID(channel,locale.replace("-","_") )
}
2

2 Answers

3
votes

You are probably calling recursively the apply method of the companion object. Try using the new operator.

 object SiteID {
    def apply(channel: String, locale: String):SiteID =
       new SiteID(channel,locale.replace("-","_") )
 }
2
votes

With the Scala case class construct, the compiler automatically generates an apply method for you with the declared parameters. If you declare another one with the same parameter types as your case class, it takes precedence over the compiler's generated one.

So as stated in another answer your apply method is calling itself recursively; a solution was provided. If you additionally need to ensure that no SiteID("bla","en-GB") value will get instantiated, you should declare the constructor of your case class as private:

case class SiteID private(channel: String, locale: String)

object SiteID {
    def apply(channel: String, locale: String):SiteID =
        new SiteID(channel,locale.replace("-","_") )
}

SiteID("bla","en-GB") //SiteID(a,en_GB)
new SiteID("bla","en-GB") //error