Aug 29, 2015

Textual description of firstImageUrl

Data types,Variable and Method declaration in Scala

In previous post we discussed fundamental of Scala and set-up Scala development environment. Here we will walk through various language construct and use REPL(Scala interpreter/interactive shell) to execute the same.

Data types:- 

Scala supports all the basic value types (primitives): Byte, Short, Int, Float, Double, Boolean, and Char.In Scala all the basic types are objects, and they’re defined under the scala package. Byte, Short, Int, Long, and Char are collectively called integral types.
The integer literals(literal is a shorthand way to describe an object) can represent decimal, hexadecimal, and octal numbers.Hexadecimal numbers start with 0x,and Long type add the suffix L or l.
scala> val hexa = 0x25
hexa: Int = 37
scala> val long= 345L
long: Long = 345
Floating-point literals are of type Float when they’re suffixed with F or f and are Double otherwise:
scala> val d = 0.0
d: Double = 0.0
scala> val f = 0.0f
f: Float = 0.0
Create a Double variable with an exponent part. To declare a variable with the value of 1 times 10 to the power of 30 (1 times 10^30), it would look like this:
scala>val exponent = 1e30
exponent: Double = 1.0E30
A character literal is a single character enclosed in quotes.
scala> val capsB = '\102'
capsB: Char = B
Printable Unicode characters can be used as variable and method names. To create a variable name ans with the value 42 using Unicode characters:
scala> val \u0065\u006e\u0079 = 45
eny: Int = 45
String object is created by using the string literal "one" and also using the new keyword, as in new String("one"). A string literal is a sequence of characters in double quotes. The characters are either
printable Unicode characters or escape sequences.
scala> val strMsg = "Hello \"Scala\""
strMsg: String = Hello "Scala"
Scala 2.10 has support for String interpolation,any token prefixed with $ or wrapped with ${...} within the string will be replaced with its corresponding values.
scala> val msgPart = "Nikhil"
msgPart: String = Nikhil
scala> s"Hello, $msgPart"
res0: String = Hello, Nikhil

Variable declaration:- 

Scala gives flexibility to create an immutable(read-only) and mutable(read-write both) variable when you declare it.
1. Using val keyword immutable variable is created(similar to final variables in Java) and var creates mutable variables.The type of variable(or function)is always written after variable and function.
2. No semicolon is required in variable declaration(In Scala, semicolon is not required until multiple statements are written in same line).
3. Scala recommends to use immutable objects whenever possible, Scala as a language doesn’t provide any restrictions.
4.The Scala interpreter infer the type of variable based on the value, but when we would like to, specify the type variable after the variable name, separating it by a colon (:).
Note:- The var and val keywords only specify whether the reference can be changed to refer to a different object (var) or not (val). In following declaration, string array reference cannot be changed but array can be modified. 
scala> val empId = 234;
empId: Int = 234

scala> empId = 234;
<console>:11: error: reassignment to val
       empId = 234;
             ^
Now create an string Array and try to modify variable reference and modify array.
scala> val stringArray:Array[String] = new Array(5);
stringArray: Array[String] = Array(null, null, null, null, null)

scala> stringArray = new Array(3);
<console>:11: error: reassignment to val
       stringArray = new Array(3);

scala> stringArray(0) ="Hello"
scala> stringArray(3) ="Scala"

scala> stringArray
res6: Array[String] = Array(Hello, null, null, Scala, null)
Create mutable object using var, reference variable can be reassigned to some other object of same type(including subclass too.)
scala> var address = "37C, LUY, NYC"
address: String = 37C, LUY, NYC

scala> address = "NYC , 34YU"
address: String = NYC , 34YU

scala> address = 12
<console>:11: error: type mismatch;
 found   : Int(12)
 required: String
       address = 12
                 ^
Declare a variable without assigning a value :- Scala placeholder character (_) to assign a default value.Default value for String is null.
scala> var defaultStr:String = _
defaultStr: String = null
lazily initialize value to a varible:- Using lazy keyword(with val only), we can initialize value of a variable when it is being used.
scala> var one = 1;
one: Int = 1

scala> lazy val lazyVal = one+ 2
lazyVal: Int = 

scala> lazyVal
res1: Int = 3
Common points for var and val keywords :-
  • We must initialize vals and vars when they are declared
  • Both keywords can be used with constructor parameters. When used as constructor parameters, the mutable or immutable variables specified will be initialized when an object is instantiated.

Function/method declaration:- 

Functions are first class citizen in Scala.To define a function in Scala, use the def keyword followed by the method name, parameters(optional argument lists), optional return type, =, and the method body.The return type of a Scala function is optional because Scala infers the return type of a function automatically, however method parameters type is mandatory.Scala type inference will figure out the type of parameters when you invoke the function but not during the function declaration.Below is syntax for function declaration.In Scala we can also pass a function as a parameter to another function,
def method_name(name: String) : String = {"Body of function"}
scala> def myFunction()= {"Hello, function call!!" }
myFunction: ()String
scala> myFunction()
res6: String = Hello, function call!!
Significance of = in function declaration:- 
1. It separates separate the signature from the method body
2. It communicates Scala compiler to infer the return type of your function. If you omit that, Scala won’t infer your return type.
scala> def myFunction(){"Hello, function call!!" }
:10: warning: a pure expression does nothing in statement position; you may be omitting necessary parentheses
       def myFunction(){"Hello, function call!!" }
                        ^
myFunction: ()Unit
As we can spot the differences, return type of function is displayed as ()Unit, Unit in Scala is equivalent to void in Java.
Nested functions declaration:- Below is sample code shows nested method and it displays count from value passed to 1.
def countTo(n: Int):Unit = {
 def count(i: Int): Unit = {
  if (i <= n) {
   println(i)
    count(i + 1)
   }
 }
 count(1)
}
countTo(5)
Scala provides a shorthand way to create a function in which you write only the function body, called function literals.Function literals are similar to anonymous function in Java.Below example createa list and multiple all element of list using foldRightmethod of List.
scala> val numberList = List(2, 4, 10)
numberList: List[Int] = List(2, 4, 10)

scala> numberList.foldRight(1){(a ,b)=> a*b}
res11: Int = 80

scala> evenNumbers.foldLeft(1) { _ * _ }
res16: Int = 80
Here (a ,b)=> a*b is an function literals, since foldRight method expect a function to passed as an argument.Scala allows us to drop the parameters in anonymous function and only have the method body to make it a function literal and parameters should be replaced with underscores (_).

Location: Hyderabad, Telangana, India