3

I'm a beginner in Scala. As far as I know, the code (0 to 9).reverse has the same meaning with:

var range : Range = 0 to 9;
range.reverse

range.reverse means to call the reverse method of the Range object with no argument, and the brackets are omitted for short.

But when I wrote range.reverse(), a compile error came out:

error: not enough arguments for method apply: (idx: Int)Int in class Range.
Unspecified value parameter idx.
              range.reverse()

Why is that? Isn't range.reverse short for range.reverse()?

Weibo Li
  • 3,565
  • 3
  • 24
  • 36
  • 4
    did you check http://stackoverflow.com/questions/6643030/what-is-the-rule-for-parenthesis-in-scala-method-invocation – mesutozer Apr 02 '14 at 10:17

1 Answers1

3
val r = (0 to 9).reverse

Compiles and does what you expect.

When you add the paranethsis, the compiler thinks you are trying to call the Range class apply method, which takes a single index argument. You have not supplied any arguments so the compile fails.

Note: method reverse defined at Range.scala like property (without '()'):

final override def reverse: Range = ...
Yuriy
  • 2,772
  • 15
  • 22
Lee
  • 142,018
  • 20
  • 234
  • 287
  • 1
    Does it mean when I write `(0 to 9).reverse()`, the compiler thinks I am calling `((0 to 9).reverse)).apply()` ? – Weibo Li Apr 02 '14 at 10:35
  • 1
    @WeiboLi - Yes it does, as the error message suggests. – Lee Apr 02 '14 at 10:44
  • `(0 to 9).reverse` is complete in itself because `reverse` method is defined without parentheses, and it returns a `Range` object. Therefore adding parentheses after that, invokes `Range.apply(...)`. Hence the compilation error. – tuxdna Apr 02 '14 at 14:02