Static function in case class (Scala)

I have a case class in a Scala application and a static function that I prefer to write in this class, as that makes sense. This is the class:

case class At (
    date : DateTime,
    id : String,
    location : Coordinate
)
{
...

   def getParsedValues(line : String) : At =
   {
      val mappedFields : Array[String] = Utils.splitFields(line)
      val atObject = new At(mappedFields)
      return atObject;
   }

...
}

And then from another Scala object, I would like to call the method getParsedValues()as a static method:

object Reader{
...
    var atObject = At.getParsedValues(line)
...
}

But he gets an error value getParsedEvent is not a member of object At

How can I make it work? Thanks

+4
source share
1 answer

The standard way to write the equivalent of static Java methods in Scala is to add this method to an object of the companion class. So:

case class At (
    date : DateTime,
    id : String,
    location : Coordinate
)

object At
{
...

   def getParsedValues(line : String) : At =
   {
      val mappedFields : Array[String] = Utils.splitFields(line)
      val atObject = new At(mappedFields)
      return atObject;
   }

...
}

Then call it, as you already do in your Readerobject.

, , , , , Array[String], factory . "" new. , atObject return atObject - . , :

def getParsedValues(line: String): At = At(Utils.splitFields(line))
+10

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


All Articles