Thursday, September 10, 2009

Assignments

Assignment in Scala follows more or less the same rules as Java and other related rules. There are some differences.

Increment operators do not work (i++). As I understand it the rational is that it is too specific an idiom. There is not an easy way to generalize it. Instead you must use i += 1.

Assignments do not return a value. For example you cannot do val i = j = 2 or while( (i = read(buffer)) > 0 ){...}.

One feature that is fairly unique in Scala is the ability to expand a case-class or other class that has an associated extractor. For details look at the previous topic Assignment and Parameter Objects.

Examples:

  1. scala> val i,j=2
  2. i: Int = 2
  3. j: Int = 2
  4. scala> val (i,j) = (1,2)
  5. i: Int = 1
  6. j: Int = 2
  7. scala> val (i,j,k) = (1,"two",3.0)
  8. i: Int = 1
  9. j: java.lang.String = two
  10. k: Double = 3.0
  11. scala> caseclass Data( name:String, age:Int, weight:Float)
  12. defined class Data
  13. scala> val Data(name, age, weight) = Data("Jesse", 133, 100f)
  14. name: String = Jesse
  15. age: Int = 133
  16. weight: Float = 100.0
  17. scala> val value = 1
  18. value: Int = 1
  19. scala> i += 1
  20. :10: error: reassignment to val
  21.        i += 1
  22.          ^
  23. scala> var variable = 1
  24. variable: Int = 1
  25. scala> variable += 1
  26. scala> println(variable)
  27. 2

No comments:

Post a Comment