Why did we define `def hello () =" world "` but can we call it as "hello"?

If we have a method:

def hello() = "world"

      

I was told that we can call it:

hello()

      

and

hello

      

They work and output world

, but why?


PS:

I see a few words in this StackOverflow question :

No, in fact, it is not. Although they both call a method with no parameters, one is a "method with null parameter lists" and the other is a "method with one empty parameter list"

But I still don't understand why this hello

will work

+3


source to share


2 answers


Scala allows you to omit parentheses on arity-0 (no arguments) methods:

You should only omit the parentheses if there are no side effects for the invokation, although



http://docs.scala-lang.org/style/method-invocation.html

+3


source


As pointed out in Oliver Shaw's answer , Scala allows parentheses to be excluded in functions with 0 arguments. As for why, it will probably make refactoring easier.

If you have a function that takes no arguments and produces no side effects , this is equivalent to an immutable value. If you always call such functions without parentheses, you can change the base function definition to a value without having to refactor it wherever it refers.

It's worth noting that definitions are val

actually modeled as 0-arity methods in Scala (unless specified beforehand with private final

).



Scala does something similar with its handling of arity-1 functions defined on classes. You can omit the period and parentheses. For example:

case class Foo(value: String) {
  def prepend(value2: String) = Foo(value2 + value)
}

Foo("one").prepend("two")
// is the same as...
Foo("one") prepend "two"

      

This is because Scala models all operators as arity-1 functions. You can rewrite 1 + 2

as 1.+(2)

and mean the same. The presentation of operators as fully functional functions has some good qualities. You can expect operator passing anywhere you might pass a function, and the operator definition is actually defined for instances of the class (unlike in C # where infix operators are actually static methods that use special syntactic sugar to let them be represented as infix).

0


source







All Articles