In Scala, is it possible to call a member method without having to call an instance of itself?
For instance, having this class:
class Model {
def action(value : String) = {
// Do action
}
}
this object implementation works:
object MyModel extends Model {
this action "doSomething"
}
But I would like to do something like this:
object MyModel extends Model {
action "doSomething"
}
As one does with Java property files, since it’s a neat way to define the state of an object.
I managed to define an alias for this:
def declare = this
but it’s the same issue of having to use a word in front of the call to the member method.
Is there an option to do this?
Yes, but you have to use parentheses:
See this answer for example for more detail about when parentheses can or cannot be omitted.
As a side note, you could also alias
thisas follows:This is often useful if you want to refer to a class’s
thisfrom inside of a nested class—it’s a bit less verbose than writingOuter.this.xas you would in Java.