Developing Functions and Arguments

As part of this topic we will see fundamental of programming – Code blocks

  • Any thing that comes in the middle of { } is considered to be block of code
  • A block of code can be assigned to a variable. Code will be evaluated first and then the value will be returned to variable
  • It can also be assigned to functions – next topic
  • Blocks can be nested
  • Each line of code need not be ended with ; as in java. ; is optional
  • But if you want to write more than one expression in one line then each expression should be ended with ;
  • In blocks, the last statement of the code-block becomes the return value

Example programme – To print from 1 to 100 line by line :

val total={
  val lb=1
  val ub=100
  val ctr=1
  var total=0
  while(ctr <=100) {
    total +=ctr
    ctr+=1
  }
  println("total is " +total)
}

Expression vs. Statement

  • Expressions are some code that yields a result. You can also say that an expression evaluates to a result or results in a value.
  • Statements are some code that does some action. This action is also called as a side effect. They do not return anything.
  • In scala, many constructs like code-blocksif-elsemethod bodies are expressions
  • Expressions always return a value.
  • The value of c in the below code snippet from gist is the value of i – j
  • The type of the last statement becomes the type of the target variable
  • Data type of sqr in the below code snippet from gist is boolean