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
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.
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.
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).
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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With