11

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

0

1 Answer 1

21

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))
2
  • The problem with this approach: If you declare a custom companion object for case classes the compiler won't add some utility methods, e.g. tupled is missing afterwards. See this question stackoverflow.com/q/25392422/935676
    – amoebe
    Commented Dec 3, 2017 at 10:57
  • Fair point, @amoebe - perhaps a separate object, 'AtUtils' or the like, could be used where this is an issue. Commented Dec 5, 2017 at 0:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.