0
scala> def judge(func: ()=> Boolean) {
     |   val result = func()
     |   println(result)
     | }
judge: (func: () => Boolean)Unit

scala> def compare = { 6 > 4 }
compare: Boolean

scala> judge(compare)
<console>:10: error: type mismatch;
 found   : Boolean
 required: () => Boolean
              judge(compare)
                    ^

scala> def compare() = { 6 > 4 }
compare: ()Boolean

scala> judge(compare)
true

What does def compare() = { 6 > 4 } means? What's difference between two 'compare' functions? I've confused.

Thank you.

GJK
  • 37,023
  • 8
  • 55
  • 74

2 Answers2

2
def compare = { 6 > 4 }

means that you create a function the compares 6 and 4 and returns a Boolean value (True).

That is so called 0-arity method.

A Scala method of 0-arity can be defined with or without parentheses (). This is used to signal the user that the method has some kind of side-effect (like printing out to std out or destroying data).

If you include the parentheses in the definition you can optionally omit them when you call the method.

Also, see Programming in Scala:

Such parameterless methods are quite common in Scala. By contrast, methods defined with empty parentheses, such as def height(): Int, are called empty-paren methods. The recommended convention is to use a parameterless method whenever there are no parameters and the method accesses mutable state only by reading fields of the containing object (in particular, it does not change mutable state).

This convention supports the uniform access principle [...]

To summarize, it is encouraged style in Scala to define methods that take no parameters and have no side effects as parameterless methods, i.e., leaving off the empty parentheses. On the other hand, you should never define a method that has side-effects without parentheses, because then invocations of that method would look like a field selection.

Additional information on this topic you can find here:

Community
  • 1
  • 1
Igor Chubin
  • 61,765
  • 13
  • 122
  • 144
0

A function always returns true.

om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
Ryo Mikami
  • 309
  • 1
  • 5