Friday, March 19, 2010

Operators

Since Scala allows one to define the behavior of operators there are some rules involving operators and assignment like +=. One of the standard method calls in most languages is i += 1.

Since i+=1(no spaces) is also valid, Scala has some rules regarding how statements like i+=1 should be broken up. Obviously we know it should be 'i' '+=' and '1'. So there is a special class of characters called operators. I don't know all of them but a few are: + - ^ * / % ! | & =( ':' is sort of part of this group but has some special properties as well).

These characters can be method names but they cannot be combined with other identifier characters.

Update: These characters can be combined with other identifier characters if there is an under score so:
  1. def x+ = 3   // not valid
  2. def x_+ = 3  // valid
  3. def +x = 3   // not valid

However these characters are special because they can be combined in a special way with '=' for a special assignment construct as shown in the next post.

(end update)

  1. scala> case class MyClass(i:Int) {
  2.      | def +(j:Int) = new MyClass(j + i)
  3.      | def -(j:Int) = new MyClass(i - j)
  4.      | def ^(j:Int) = MyClass(j)
  5.      | def +|(j:Int) = new MyClass(j + i / 3)
  6.      | }
  7.  
  8.  scala> val c = MyClass(3)
  9.  c: MyClass = MyClass(3)
  10.  scala> c + 4
  11.  res26: MyClass = MyClass(7)
  12.  scala> c-2 
  13.  res27: MyClass = MyClass(1)
  14.  scala> c -6
  15.  res28: MyClass = MyClass(-3)
  16.  scala> c ^ 3
  17.  res29: MyClass = MyClass(3)
  18.  scala> c+|5
  19.  res31: MyClass = MyClass(6)

3 comments:

  1. Actually, the rule is rather simpler than that. In a valid identifier, any non-alphanumeric characters must follow alphanumeric ones, and be separated from them by an underscore.

    So, "+a" is not valid because "a" is after a non-alphanumeric character. "a+" isn't valid because "a" and "+" are not separated by an underscore "th15_15_an_weird_example_#@%&*" is valid.

    ALL unicode characters are valid, with the exception of a few reserved ones: ()[]{}\.,;

    I can't recall right now any other character that is not allowed in an identifier, but there could be one.

    ReplyDelete
  2. (pedantically) presumably no whitespace characters are allowed, according to some definition of 'whitespace'.

    ReplyDelete
  3. @Daniel. I am not discussing identifiers specifically operators. They are special because you can do:

    var c = MyClass(1)

    c += 3

    but if there are any alphanumerics you cannot do that:

    c x= 4

    will not work for a method called x because it will think the method name is x= not x.

    ReplyDelete