2

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
pablisco
  • 14,027
  • 4
  • 48
  • 70

1 Answers1

8

Yes, but you have to use parentheses:

object MyModel extends Model {
    action("doSomething")
}

See this answer for example for more detail about when parentheses can or cannot be omitted.

As a side note, you could also alias this as follows:

object MyModel extends Model { declare =>
  declare action "doSomething"
}

This is often useful if you want to refer to a class's this from inside of a nested class—it's a bit less verbose than writing Outer.this.x as you would in Java.

Community
  • 1
  • 1
Travis Brown
  • 138,631
  • 12
  • 375
  • 680