Monday, August 31, 2009

Java vs Scala Control Structures

This topic is mainly for completeness. We will quickly cover the standard control structures you find in Java and see how they are the same or different in Scala.

The first thing to note is that in Scala 2.7 there is no break keyword. In Scala 2.8 there is a break control structure but it is slightly different than the Java break keyword. We will encounter that topic in a later lesson. The control structures I will quickly cover are: do-while, while, for and if.

For information about the Java case statement take a look at the several matching topics covered now and in the future.

Note: The Java ternary if statement does not exist in Scala instead the standard if statement is to be used. It is slightly more verbose but returns a value in the same way as a ternary if statement.
  1. scala>var i = 0;
  2. i: Int = 0
  3. scala>while( i<3 ){
  4.      | println( i )
  5.      | i += 1
  6.      | }
  7. 0
  8. 1
  9. 2
  10. scala> i = 0
  11. i: Int = 0
  12. scala> do {
  13.      | println( i )
  14.      | i += 1
  15.      | } while (i<3)
  16. 0
  17. 1
  18. 2
  19. scala>for(j <- 0 until 3) println (j)  
  20. 0
  21. 1
  22. 2
  23. scala>if (i<3)
  24. more
  25. scala>val result = if (i<3)
  26. result: Int = 10
  27. scala> println (result)
  28. 10
  29. scala>if (i>10) println(1)
  30. scala>if (i<10)
  31. 1
  32. // Note that the return value is ().  You can only get a meaningful return value if there is an else-clause.
  33. scala>val r = if (i<10)>
  34. r: Unit = ()
  35. scala> println(r)
  36. ()

No comments:

Post a Comment