In scala, how can I call a single parameter method using space in the body of the anonymous class?
add "Answer3"
below is not working
trait Question {
def add(answer:String):Unit = {
println("Received the answer=" answer)
}
}
object Test {
val question:Question = new Question {
this add "Answer1" // working
add("Answer2") // working
add "Answer3" // NOT working, why? -> error: ';' expected but string literal found.
}
}
CodePudding user response:
You're trying to mix two different, and conflicting, convenience syntax options.
instance.method(argument)
... can be expressed as ...
instance method argument
... and, if the method()
takes no argument then that can also be expressed with spaces, but the parser needs a little help.
instance method;
On a separate track, if the instance
is this
then that can be dropped.
method(argument)
But you can't drop the parentheses because the parser tries to interpret that as instance method
and fails.