zjffdu
zjffdu

Reputation: 28954

Scala method syntax problem

I am learning scala, and meet a little problem. I want to use the String method stripMargin as following. But I can not add parenthesis on this method. I remember that no-argument method's parenthesis is optional, so here why I can not add parenthesis ?

val str=""" hello world
    |" ANd soe"
    |" to world"""

println(str.stripMargin())  // won't compile
println(str.stripMargin)  // compiles successfully

Upvotes: 0

Views: 129

Answers (1)

Jean-Philippe Pellet
Jean-Philippe Pellet

Reputation: 60016

If the method without parameters in define with (), then writing () is optional. If the method is defined without (), then adding () is not allowed (or, rather, is interpreted as if you were calling apply() on the returned result).

Good practice recommends that a method without side effects be defined without (), and to keep () both at definition site and call site when it has side effects.

Upvotes: 4

Related Questions