In this article we present several programming pitfalls Scala users may fall into.
Scala supports special syntax for procedures (see SLS 4.6.3):
write
:
trait Writer { def write(str: String) } object Terminal extends Writer { def write(str: String) { println(str) } }
trait Writer { def write(str: String): Unit } object Terminal extends Writer { def write(str: String): Unit = { println(str) } }
object unitvalue extends Application { def twice1(x: Int) { 2 * x } // procedure def twice2(x: Int) = { 2 * x } // function println(twice1(3)) // prints "()" println(twice2(3)) // prints "6" }
Scala is a line-oriented language where statements may be terminated by semicolons or newlines (see SLS 1.2).
Omitting one of semicolons in the code below will eg. generate a compiler error.
object semicolons extends App { println(1); // [1] { println(2) } val i = 3; // [2] { println(i) } }
The compiler aborts with the error message error: Unit does not
take parameters
in case [1] and error: Int(3) does not take
parameters
in case [2].
The rules for pattern matching further distinguish between variable identifiers, which start with a lower case letter, and constant identifiers, which do not.
object varpats extends App { var liftID = 22 var doorID = 35 def test1(id: Int, n: Int): String = { (id, n) match { case (liftID, n) => "case 1: "+id case _ => "case _: "+id } } def test2(id: Int, n: Int): String = { val LiftID = liftID (id, n) match { case (LiftID, n) => "case 1: "+id case _ => "case _: "+id } } println("[test1] "+test1(doorID, 3)) println("[test2] "+test2(doorID, 3)) }
[test1] case 1: 35 [test2] case _: 35