9

I was going through the wonderful book Programming in Scala when I came across a piece of code that just doesn't make sense to me:

def above(that: Element): Element = {
    val this1 = this widen that.width
    val that1 = that widen this.width
    elem(this1.contents ++ that1.contents)
}

Note line 2 and 3:

val this1 = this widen that.width 

It seems like I should be able to replace this with:

val this1 = this.widen that.width

However, when I try to compile this change, it gives the following error:

error: ';' expected but '.' found.
val this1 = this.widen that.width ^

Why is this syntax unacceptable?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Zack Marrapese
  • 12,072
  • 9
  • 51
  • 69
  • 1
    Possible duplicates: http://stackoverflow.com/questions/1181533/what-are-the-precise-rules-for-when-you-can-omit-parenthesis-dots-braces-fu and http://stackoverflow.com/questions/1006967/scala-which-characters-can-i-omit – Daniel C. Sobral Aug 05 '09 at 17:08

3 Answers3

17

Line 2 uses the method widen as an operator, instead of using it as a method in the Java way:

val this1 = this.widen(that.width)

The error occurs because you've left out the parentheses, which you can only do when you use a method in operator notation. You can't do this for example:

"a".+ "b" // error: ';' expected but string literal found.

Instead you should write

"a".+ ("b")

Actually you can do this with integers, but that's beyond the scope of this question.

Read more:

  • Chapter 5 section 3 of your book is about the operator notation, at least in the first edition, version 5
  • A Tour of Scala: Operators
André Laszlo
  • 15,169
  • 3
  • 63
  • 81
3

I haven't tried it but maybe this works: val this1 = this.widen(that.width)

widen is probably a method taking one parameter (plus the this reference), such methods can be used like operators as in your first sample code.

Jörn Horstmann
  • 33,639
  • 11
  • 75
  • 118
2

When you use a dot you are using dot-style for method invocation. When you don't, you are using operator-style. You can't mix both syntaxes for the very same method invocation, though you can mix the two for different invocations -- such as that.width used as a parameter in the operator style invocation of widen.

Please refer to Which characters can I omit in Scala? or What are the precise rules for when you can omit parenthesis, dots, braces, = (functions), etc.?.

Community
  • 1
  • 1
Daniel C. Sobral
  • 295,120
  • 86
  • 501
  • 681