Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static function in case class (Scala)

I have a case class in a Scala application, and a static function which I prefer to write within that class, as it makes the best 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 static method:

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

But it get an error value getParsedEvent is not a member of object At

How can I make it work? Thanks

like image 812
Yoav Avatar asked Nov 18 '15 08:11

Yoav


People also ask

How do I declare a static method in Scala?

In Scala there are no static methods: all methods are defined over an object, be it an instance of a class or a singleton, as the one you defined in your question.

Can Scala classes have static members?

In Scala, we use class keyword to define instance members and object keyword to define static members. Scala does not have static keyword, but still we can define them by using object keyword. The main design decision about this is that the clear separation between instance and static members.

Can Case classes contain member functions?

It can contain both state and functionality. Case classes are like data POJO in Java. classes that hold state, which can be used by functions (usually in other classes).

Can case class have methods Scala?

Case Classes You can construct them without using new. case classes automatically have equality and nice toString methods based on the constructor arguments. case classes can have methods just like normal classes.


1 Answers

The standard way to write the equivalent of Java static methods in Scala is to add the method to the class's companion object. 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 this as you already do in your Reader object.

Also, the constructor variant you will presumably need that takes an Array[String] might be better coded as a factory method in that same companion object. The middle line of your "static" method would then drop the new keyword. Also, you can drop the assignment to atObject and the return atObject line - the result of the last expression of a method is automatically taken as the return value for the method. Indeed, the whole method can be written as just:

def getParsedValues(line: String): At = At(Utils.splitFields(line))
like image 148
Shadowlands Avatar answered Sep 28 '22 01:09

Shadowlands