Monday, August 3, 2009

Programming In Scala: Chapter#2,3 notes

I did a quick reading of above mentioned chapters from Programming in Scala by Martin Odersky and noted a few key things...

A scala compiler does not infer function parameter types, it does so only for the function return type.

If function is recursive, you must specify its return type.

If function body has only a single expression then you can optionally leave out the curly braces.

"Unit" type is returned from the functions that don't do anything useful, its like java void.

If a function literal consists of only one expression that takes the argument then we may skip writing the argument explicitly. Let me give an example..

array.forEach(arg => println(arg))

is equivalent to

array.forEach(println)
There are two kinds of variables in scala, var and val. val are final and can't be reassigned. Although the variables defined with val are final. but the object, they are refering to, might very well be mutable.

If a method takes only one parameter then you can call it without using the parenthesis. In reality there are no operators in scala(as in scheme:)) and the op looking variables are actually functions taking advantage of the mentioned fact. For example, "1 + 2" is actually "1.+(2)"
If a method is used in operator notation like a op b, then it means a.op(b) except in the case where method name ends with colon and then "a op: b" mean b.op:(a)

If you say greet("hi") on a variable, it automatically gets converted to greet.apply("hi") that is why array elements can be accessed with array(index) syntax. Similarly greet("hi")=value is transformed into greet.update("hi",value).

Pretty much for every data structure, scala provides both, mutable and immutable implementations.

Tuples can be used for multiple value return from a function.

semicolons are mostly optional.

Scala supports functional as well as imperative programming but encourages to use functional unless its justifiable to use the other one and hence prefer val over var, immutable object over mutable object and functions with no side effects over functions with side effects.

No comments:

Post a Comment