Scala – Functions

Scala – Functions ”; Previous Next A function is a group of statements that perform a task. You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically, the division usually is so that each function performs a specific task. Scala has both functions and methods and we use the terms method and function interchangeably with a minor difference. A Scala method is a part of a class which has a name, a signature, optionally some annotations, and some bytecode where as a function in Scala is a complete object which can be assigned to a variable. In other words, a function, which is defined as a member of some object, is called a method. A function definition can appear anywhere in a source file and Scala permits nested function definitions, that is, function definitions inside other function definitions. Most important point to note is that Scala function”s name can have characters like +, ++, ~, &,-, –, , /, :, etc. Function Declarations A Scala function declaration has the following form − def functionName ([list of parameters]) : [return type] Methods are implicitly declared abstract if you don’t use the equals sign and the method body. Function Definitions A Scala function definition has the following form − Syntax def functionName ([list of parameters]) : [return type] = { function body return [expr] } Here, return type could be any valid Scala data type and list of parameters will be a list of variables separated by comma and list of parameters and return type are optional. Very similar to Java, a return statement can be used along with an expression in case function returns a value. Following is the function which will add two integers and return their sum − Syntax object add { def addInt( a:Int, b:Int ) : Int = { var sum:Int = 0 sum = a + b return sum } } A function, that does not return anything can return a Unit that is equivalent to void in Java and indicates that function does not return anything. The functions which do not return anything in Scala, they are called procedures. Syntax Here is the syntax − object Hello{ def printMe( ) : Unit = { println(“Hello, Scala!”) } } Calling Functions Scala provides a number of syntactic variations for invoking methods. Following is the standard way to call a method − functionName( list of parameters ) If a function is being called using an instance of the object, then we would use dot notation similar to Java as follows − [instance.]functionName( list of parameters ) Try the following example program to define and then call the same function. Example object Demo { def main(args: Array[String]) { println( “Returned Value : ” + addInt(5,7) ); } def addInt( a:Int, b:Int ) : Int = { var sum:Int = 0 sum = a + b return sum } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output Returned Value : 12 Scala functions are the heart of Scala programming and that”s why Scala is assumed as a functional programming language. Following are few important concepts related to Scala functions which should be understood by a Scala programmer. Functions Call-by-Name Functions with Named Arguments Function with Variable Arguments Recursion Functions Default Parameter Values Higher-Order Functions Nested Functions Anonymous Functions Partially Applied Functions Currying Functions Print Page Previous Next Advertisements ”;

Scala – Quick Guide

Scala – Quick Guide ”; Previous Next Scala – Overview Scala, short for Scalable Language, is a hybrid functional programming language. It was created by Martin Odersky. Scala smoothly integrates the features of object-oriented and functional languages. Scala is compiled to run on the Java Virtual Machine. Many existing companies, who depend on Java for business critical applications, are turning to Scala to boost their development productivity, applications scalability and overall reliability. Here we have presented a few points that makes Scala the first choice of application developers. Scala is object-oriented Scala is a pure object-oriented language in the sense that every value is an object. Types and behavior of objects are described by classes and traits which will be explained in subsequent chapters. Classes are extended by subclassing and a flexible mixin-based composition mechanism as a clean replacement for multiple inheritance. Scala is functional Scala is also a functional language in the sense that every function is a value and every value is an object so ultimately every function is an object. Scala provides a lightweight syntax for defining anonymous functions, it supports higher-order functions, it allows functions to be nested, and supports currying. These concepts will be explained in subsequent chapters. Scala is statically typed Scala, unlike some of the other statically typed languages (C, Pascal, Rust, etc.), does not expect you to provide redundant type information. You don”t have to specify a type in most cases, and you certainly don”t have to repeat it. Scala runs on the JVM Scala is compiled into Java Byte Code which is executed by the Java Virtual Machine (JVM). This means that Scala and Java have a common runtime platform. You can easily move from Java to Scala. The Scala compiler compiles your Scala code into Java Byte Code, which can then be executed by the ”scala” command. The ”scala” command is similar to the java command, in that it executes your compiled Scala code. Scala can Execute Java Code Scala enables you to use all the classes of the Java SDK and also your own custom Java classes, or your favorite Java open source projects. Scala can do Concurrent & Synchronize processing Scala allows you to express general programming patterns in an effective way. It reduces the number of lines and helps the programmer to code in a type-safe way. It allows you to write codes in an immutable manner, which makes it easy to apply concurrency and parallelism (Synchronize). Scala vs Java Scala has a set of features that completely differ from Java. Some of these are − All types are objects Type inference Nested Functions Functions are objects Domain specific language (DSL) support Traits Closures Concurrency support inspired by Erlang Scala Web Frameworks Scala is being used everywhere and importantly in enterprise web applications. You can check a few of the most popular Scala web frameworks − The Lift Framework The Play framework The Bowler framework Scala – Environment Setup Scala can be installed on any UNIX flavored or Windows based system. Before you start installing Scala on your machine, you must have Java 1.8 or greater installed on your computer. Follow the steps given below to install Scala. Step 1: Verify Your Java Installation First of all, you need to have Java Software Development Kit (SDK) installed on your system. To verify this, execute any of the following two commands depending on the platform you are working on. If the Java installation has been done properly, then it will display the current version and specification of your Java installation. A sample output is given in the following table. Platform Command Sample Output Windows Open Command Console and type − >java –version Java version “1.8.0_31” Java (TM) SE Run Time Environment (build 1.8.0_31-b31) Java Hotspot (TM) 64-bit Server VM (build 25.31-b07, mixed mode) Linux Open Command terminal and type − $java –version Java version “1.8.0_31” Open JDK Runtime Environment (rhel-2.8.10.4.el6_4-x86_64) Open JDK 64-Bit Server VM (build 25.31-b07, mixed mode) We assume that the readers of this tutorial have Java SDK version 1.8.0_31 installed on their system. In case you do not have Java SDK, download its current version from http://www.oracle.com/technetwork/java/javase/downloads/index.html and install it. Step 2: Set Your Java Environment Set the environment variable JAVA_HOME to point to the base directory location where Java is installed on your machine. For example, Sr.No Platform & Description 1 Windows Set JAVA_HOME to C:ProgramFilesjavajdk1.7.0_60 2 Linux Export JAVA_HOME=/usr/local/java-current Append the full path of Java compiler location to the System Path. Sr.No Platform & Description 1 Windows Append the String “C:Program FilesJavajdk1.7.0_60bin” to the end of the system variable PATH. 2 Linux Export PATH=$PATH:$JAVA_HOME/bin/ Execute the command java -version from the command prompt as explained above. Step 3: Install Scala You can download Scala from http://www.scala-lang.org/downloads. At the time of writing this tutorial, I downloaded ‘scala-2.11.5-installer.jar’. Make sure you have admin privilege to proceed. Now, execute the following command at the command prompt − Platform Command & Output Description Windows >java –jar scala-2.11.5-installer.jar> This command will display an installation wizard, which will guide you to install Scala on your windows machine. During installation, it will ask for license agreement, simply accept it and further it will ask a path where Scala will be installed. I selected default given path “C:Program FilesScala”, you can select a suitable path as per your convenience. Linux Command − $java –jar scala-2.9.0.1-installer.jar Output − Welcome to the installation of Scala 2.9.0.1! The homepage is at − http://Scala-lang.org/ press 1 to continue, 2 to quit, 3 to redisplay 1………………………………………… [ Starting to unpack ] [ Processing package: Software Package Installation (1/1) ] [ Unpacking finished ] [ Console installation done ] During installation, it will ask for license agreement, to accept it type 1 and it will ask a path where Scala will be installed. I entered /usr/local/share, you can select a suitable path as per your convenience. Finally, open a new command prompt and type Scala -version and press Enter. You should see the

Scala – Regular Expressions

Scala – Regular Expressions ”; Previous Next This chapter explains how Scala supports regular expressions through Regex class available in the scala.util.matching package. Try the following example program where we will try to find out word Scala from a statement. Example import scala.util.matching.Regex object Demo { def main(args: Array[String]) { val pattern = “Scala”.r val str = “Scala is Scalable and cool” println(pattern findFirstIn str) } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output Some(Scala) We create a String and call the r( ) method on it. Scala implicitly converts the String to a RichString and invokes that method to get an instance of Regex. To find a first match of the regular expression, simply call the findFirstIn() method. If instead of finding only the first occurrence we would like to find all occurrences of the matching word, we can use the findAllIn( ) method and in case there are multiple Scala words available in the target string, this will return a collection of all matching words. You can make use of the mkString( ) method to concatenate the resulting list and you can use a pipe (|) to search small and capital case of Scala and you can use Regex constructor instead or r() method to create a pattern. Try the following example program. Example import scala.util.matching.Regex object Demo { def main(args: Array[String]) { val pattern = new Regex(“(S|s)cala”) val str = “Scala is scalable and cool” println((pattern findAllIn str).mkString(“,”)) } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output Scala,scala If you would like to replace matching text, we can use replaceFirstIn( ) to replace the first match or replaceAllIn( ) to replace all occurrences. Example object Demo { def main(args: Array[String]) { val pattern = “(S|s)cala”.r val str = “Scala is scalable and cool” println(pattern replaceFirstIn(str, “Java”)) } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output Java is scalable and cool Forming Regular Expressions Scala inherits its regular expression syntax from Java, which in turn inherits most of the features of Perl. Here are just some examples that should be enough as refreshers − Following is the table listing down all the regular expression Meta character syntax available in Java. Subexpression Matches ^ Matches beginning of line. $ Matches end of line. . Matches any single character except newline. Using m option allows it to match newline as well. […] Matches any single character in brackets. [^…] Matches any single character not in brackets \A Beginning of entire string \z End of entire string \Z End of entire string except allowable final line terminator. re* Matches 0 or more occurrences of preceding expression. re+ Matches 1 or more of the previous thing re? Matches 0 or 1 occurrence of preceding expression. re{ n} Matches exactly n number of occurrences of preceding expression. re{ n,} Matches n or more occurrences of preceding expression. re{ n, m} Matches at least n and at most m occurrences of preceding expression. a|b Matches either a or b. (re) Groups regular expressions and remembers matched text. (?: re) Groups regular expressions without remembering matched text. (?> re) Matches independent pattern without backtracking. \w Matches word characters. \W Matches nonword characters. \s Matches whitespace. Equivalent to [tnrf]. \S Matches nonwhitespace. \d Matches digits. Equivalent to [0-9]. \D Matches nondigits. \A Matches beginning of string. \Z Matches end of string. If a newline exists, it matches just before newline. \z Matches end of string. \G Matches point where last match finished. \n Back-reference to capture group number “n” \b Matches word boundaries when outside brackets. Matches backspace (0x08) when inside brackets. \B Matches nonword boundaries. \n, \t, etc. Matches newlines, carriage returns, tabs, etc. \Q Escape (quote) all characters up to \E \E Ends quoting begun with \Q Regular-Expression Examples Example Description . Match any character except newline [Rr]uby Match “Ruby” or “ruby” rub[ye] Match “ruby” or “rube” [aeiou] Match any one lowercase vowel [0-9] Match any digit; same as [0123456789] [a-z] Match any lowercase ASCII letter [A-Z] Match any uppercase ASCII letter [a-zA-Z0-9] Match any of the above [^aeiou] Match anything other than a lowercase vowel [^0-9] Match anything other than a digit \d Match a digit: [0-9] \D Match a nondigit: [^0-9] \s Match a whitespace character: [ trnf] \S Match nonwhitespace: [^ trnf] \w Match a single word character: [A-Za-z0-9_] \W Match a nonword character: [^A-Za-z0-9_] ruby? Match “rub” or “ruby”: the y is optional ruby* Match “rub” plus 0 or more ys ruby+ Match “rub” plus 1 or more ys \d{3} Match exactly 3 digits \d{3,} Match 3 or more digits \d{3,5} Match 3, 4, or 5 digits \D\d+ No group: + repeats \d (\D\d)+/ Grouped: + repeats \Dd pair ([Rr]uby(, )?)+ Match “Ruby”, “Ruby, ruby, ruby”, etc. Note − that every backslash appears twice in the string above. This is because in Java and Scala a single backslash is an escape character in a string literal, not a regular character that shows up in the string. So instead of ‘’, you need to write ‘\’ to get a single backslash in the string. Try the following example program. Example import scala.util.matching.Regex object Demo { def main(args: Array[String]) { val pattern = new Regex(“abl[ae]\d+”) val str = “ablaw is able1 and cool” println((pattern findAllIn str).mkString(“,”)) } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output able1 Print Page Previous Next Advertisements ”;

Scala – IF ELSE

Scala – IF ELSE Statements ”; Previous Next This chapter takes you through the conditional construction statements in Scala programming. Following is the general form of a typical decision making IF…ELSE structure found in most of the programming languages. Flow Chart The following is a flow chart diagram for conditional statement. if Statement ‘if’ statement consists of a Boolean expression followed by one or more statements. Syntax The syntax of an ‘if’ statement is as follows. if(Boolean_expression) { // Statements will execute if the Boolean expression is true } If the Boolean expression evaluates to true then the block of code inside the ‘if’ expression will be executed. If not, the first set of code after the end of the ‘if’ expression (after the closing curly brace) will be executed. Try the following example program to understand conditional expressions (if expression) in Scala Programming Language. Example object Demo { def main(args: Array[String]) { var x = 10; if( x < 20 ){ println(“This is if statement”); } } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output This is if statement If-else Statement An ‘if’ statement can be followed by an optional else statement, which executes when the Boolean expression is false. Syntax The syntax of a if…else is − if(Boolean_expression){ //Executes when the Boolean expression is true } else{ //Executes when the Boolean expression is false } Try the following example program to understand conditional statements (if- else statement) in Scala Programming Language. Example object Demo { def main(args: Array[String]) { var x = 30; if( x < 20 ){ println(“This is if statement”); } else { println(“This is else statement”); } } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output This is else statement If-else-if-else Statement An ”if” statement can be followed by an optional ”else if…else” statement, which is very useful to test various conditions using single if…else if statement. When using if , else if , else statements there are few points to keep in mind. An ”if” can have zero or one else”s and it must come after any else if”s. An ”if” can have zero to many else if”s and they must come before the else. Once an else if succeeds, none of he remaining else if”s or else”s will be tested. Syntax The following is the syntax of an ‘if…else if…else’ is as follows − if(Boolean_expression 1){ //Executes when the Boolean expression 1 is true } else if(Boolean_expression 2){ //Executes when the Boolean expression 2 is true } else if(Boolean_expression 3){ //Executes when the Boolean expression 3 is true } else { //Executes when the none of the above condition is true. } Try the following example program to understand conditional statements (if- else- if- else statement) in Scala Programming Language. Example object Demo { def main(args: Array[String]) { var x = 30; if( x == 10 ){ println(“Value of X is 10”); } else if( x == 20 ){ println(“Value of X is 20”); } else if( x == 30 ){ println(“Value of X is 30”); } else{ println(“This is else statement”); } } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output Value of X is 30 Nested if-else Statement It is always legal to nest if-else statements, which means you can use one if or else-if statement inside another if or else-if statement. Syntax The syntax for a nested if-else is as follows − if(Boolean_expression 1){ //Executes when the Boolean expression 1 is true if(Boolean_expression 2){ //Executes when the Boolean expression 2 is true } } Try the following example program to understand conditional statements (nested- if statement) in Scala Programming Language. Example object Demo { def main(args: Array[String]) { var x = 30; var y = 10; if( x == 30 ){ if( y == 10 ){ println(“X = 30 and Y = 10″); } } } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output X = 30 and Y = 10 Print Page Previous Next Advertisements ”;

Scala – Collections

Scala – Collections ”; Previous Next Scala has a rich set of collection library. Collections are containers of things. Those containers can be sequenced, linear sets of items like List, Tuple, Option, Map, etc. The collections may have an arbitrary number of elements or be bounded to zero or one element (e.g., Option). Collections may be strict or lazy. Lazy collections have elements that may not consume memory until they are accessed, like Ranges. Additionally, collections may be mutable (the contents of the reference can change) or immutable (the thing that a reference refers to is never changed). Note that immutable collections may contain mutable items. For some problems, mutable collections work better, and for others, immutable collections work better. When in doubt, it is better to start with an immutable collection and change it later if you need mutable ones. This chapter throws light on the most commonly used collection types and most frequently used operations over those collections. Sr.No Collections with Description 1 Scala Lists Scala”s List[T] is a linked list of type T. 2 Scala Sets A set is a collection of pairwise different elements of the same type. 3 Scala Maps A Map is a collection of key/value pairs. Any value can be retrieved based on its key. 4 Scala Tuples Unlike an array or list, a tuple can hold objects with different types. 5 Scala Options Option[T] provides a container for zero or one element of a given type. 6 Scala Iterators An iterator is not a collection, but rather a way to access the elements of a collection one by one. Print Page Previous Next Advertisements ”;

Scala – Classes & Objects

Scala – Classes & Objects ”; Previous Next This chapter takes you through how to use classes and objects in Scala programming. A class is a blueprint for objects. Once you define a class, you can create objects from the class blueprint with the keyword new. Through the object you can use all functionalities of the defined class. The following diagram demonstrates the class and object by taking an example of class student, which contains the member variables (name and roll no) and member methods (setName() and setRollNo()). Finally all are members of the class. Class is a blue print and objects are real here. In the following diagram, Student is a class and Harini, John, and Maria are the objects of Student class, those are having name and roll-number. Basic Class Following is a simple syntax to define a basic class in Scala. This class defines two variables x and y and a method: move, which does not return a value. Class variables are called, fields of the class and methods are called class methods. The class name works as a class constructor which can take a number of parameters. The above code defines two constructor arguments, xc and yc; they are both visible in the whole body of the class. Syntax class Point(xc: Int, yc: Int) { var x: Int = xc var y: Int = yc def move(dx: Int, dy: Int) { x = x &plus; dx y = y &plus; dy println (“Point x location : ” + x); println (“Point y location : ” + y); } } As mentioned earlier in this chapter, you can create objects using a keyword new and then you can access class fields and methods as shown below in the example − Example import java.io._ class Point(val xc: Int, val yc: Int) { var x: Int = xc var y: Int = yc def move(dx: Int, dy: Int) { x = x &plus; dx y = y &plus; dy println (“Point x location : ” &plus; x); println (“Point y location : ” &plus; y); } } object Demo { def main(args: Array[String]) { val pt = new Point(10, 20); // Move to a new location pt.move(10, 10); } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output Point x location : 20 Point y location : 30 Extending a Class You can extend a base Scala class and you can design an inherited class in the same way you do it in Java (use extends key word), but there are two restrictions: method overriding requires the override keyword, and only the primary constructor can pass parameters to the base constructor. Let us extend our above class and add one more class method. Example Let us take an example of two classes Point class (as same example as above) and Location class is inherited class using extends keyword. Such an ‘extends’ clause has two effects: it makes Location class inherit all non-private members from Point class, and it makes the type Location a subtype of the type Point class. So here the Point class is called superclass and the class Location is called subclass. Extending a class and inheriting all the features of a parent class is called inheritance but Scala allows the inheritance from just one class only. Note − Methods move() method in Point class and move() method in Location class do not override the corresponding definitions of move since they are different definitions (for example, the former take two arguments while the latter take three arguments). Try the following example program to implement inheritance. import java.io._ class Point(val xc: Int, val yc: Int) { var x: Int = xc var y: Int = yc def move(dx: Int, dy: Int) { x = x &plus; dx y = y &plus; dy println (“Point x location : ” &plus; x); println (“Point y location : ” &plus; y); } } class Location(override val xc: Int, override val yc: Int, val zc :Int) extends Point(xc, yc){ var z: Int = zc def move(dx: Int, dy: Int, dz: Int) { x = x &plus; dx y = y &plus; dy z = z &plus; dz println (“Point x location : ” &plus; x); println (“Point y location : ” &plus; y); println (“Point z location : ” &plus; z); } } object Demo { def main(args: Array[String]) { val loc = new Location(10, 20, 15); // Move to a new location loc.move(10, 10, 5); } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output Point x location : 20 Point y location : 30 Point z location : 20 Implicit Classes Implicit classes allow implicit conversations with class’s primary constructor when the class is in scope. Implicit class is a class marked with ‘implicit’ keyword. This feature is introduced in Scala 2.10. Syntax − The following is the syntax for implicit classes. Here implicit class is always in the object scope where all method definitions are allowed because implicit class cannot be a top level class. Syntax object <object name> { implicit class <class name>(<Variable>: Data type) { def <method>(): Unit = } } Example Let us take an example of an implicit class named IntTimes with the method times(). It means the times () contain a loop transaction that will execute the given statement in number of times that we give. Let us assume the given statement is “4 times println (“Hello”)” means the println (“”Hello”) statement will execute 4 times. The following is the program for the given example. In this example two object classes are used (Run and Demo) so that we have to save those two classes in different files with their respective names as follows. Run.scala − Save the following program in Run.scala. object Run { implicit class IntTimes(x: Int) {

Scala – Access Modifiers

Scala – Access Modifiers ”; Previous Next This chapter takes you through the Scala access modifiers. Members of packages, classes or objects can be labeled with the access modifiers private and protected, and if we are not using either of these two keywords, then access will be assumed as public. These modifiers restrict accesses to the members to certain regions of code. To use an access modifier, you include its keyword in the definition of members of package, class or object as we will see in the following section. Private Members A private member is visible only inside the class or object that contains the member definition. Following is the example code snippet to explain Private member − Example class Outer { class Inner { private def f() { println(“f”) } class InnerMost { f() // OK } } (new Inner).f() // Error: f is not accessible } In Scala, the access (new Inner). f() is illegal because f is declared private in Inner and the access is not from within class Inner. By contrast, the first access to f in class Innermost is OK, because that access is contained in the body of class Inner. Java would permit both accesses because it lets an outer class access private members of its inner classes. Protected Members A protected member is only accessible from subclasses of the class in which the member is defined. Following is the example code snippet to explain protected member − Example package p { class Super { protected def f() { println(“f”) } } class Sub extends Super { f() } class Other { (new Super).f() // Error: f is not accessible } } The access to f in class Sub is OK because f is declared protected in ‘Super’ class and ‘Sub’ class is a subclass of Super. By contrast the access to f in ‘Other’ class is not permitted, because class ‘Other’ does not inherit from class ‘Super’. In Java, the latter access would be still permitted because ‘Other’ class is in the same package as ‘Sub’ class. Public Members Unlike private and protected members, it is not required to specify Public keyword for Public members. There is no explicit modifier for public members. Such members can be accessed from anywhere. Following is the example code snippet to explain public member − Example class Outer { class Inner { def f() { println(“f”) } class InnerMost { f() // OK } } (new Inner).f() // OK because now f() is public } Scope of Protection Access modifiers in Scala can be augmented with qualifiers. A modifier of the form private[X] or protected[X] means that access is private or protected “up to” X, where X designates some enclosing package, class or singleton object. Consider the following example − Example package society { package professional { class Executive { private[professional] var workDetails = null private[society] var friends = null private[this] var secrets = null def help(another : Executive) { println(another.workDetails) println(another.secrets) //ERROR } } } } Note − the following points from the above example − Variable workDetails will be accessible to any class within the enclosing package professional. Variable friends will be accessible to any class within the enclosing package society. Variable secrets will be accessible only on the implicit object within instance methods (this). Print Page Previous Next Advertisements ”;

Scala – Pattern Matching

Scala – Pattern Matching ”; Previous Next Pattern matching is the second most widely used feature of Scala, after function values and closures. Scala provides great support for pattern matching, in processing the messages. A pattern match includes a sequence of alternatives, each starting with the keyword case. Each alternative includes a pattern and one or more expressions, which will be evaluated if the pattern matches. An arrow symbol => separates the pattern from the expressions. Try the following example program, which shows how to match against an integer value. Example object Demo { def main(args: Array[String]) { println(matchTest(3)) } def matchTest(x: Int): String = x match { case 1 => “one” case 2 => “two” case _ => “many” } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output many The block with the case statements defines a function, which maps integers to strings. The match keyword provides a convenient way of applying a function (like the pattern matching function above) to an object. Try the following example program, which matches a value against patterns of different types. Example object Demo { def main(args: Array[String]) { println(matchTest(“two”)) println(matchTest(“test”)) println(matchTest(1)) } def matchTest(x: Any): Any = x match { case 1 => “one” case “two” => 2 case y: Int => “scala.Int” case _ => “many” } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output 2 many one Matching using Case Classes The case classes are special classes that are used in pattern matching with case expressions. Syntactically, these are standard classes with a special modifier: case. Try the following, it is a simple pattern matching example using case class. Example object Demo { def main(args: Array[String]) { val alice = new Person(“Alice”, 25) val bob = new Person(“Bob”, 32) val charlie = new Person(“Charlie”, 32) for (person <- List(alice, bob, charlie)) { person match { case Person(“Alice”, 25) => println(“Hi Alice!”) case Person(“Bob”, 32) => println(“Hi Bob!”) case Person(name, age) => println( “Age: ” &plus; age &plus; ” year, name: ” &plus; name &plus; “?”) } } } case class Person(name: String, age: Int) } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output Hi Alice! Hi Bob! Age: 32 year, name: Charlie? Adding the case keyword causes the compiler to add a number of useful features automatically. The keyword suggests an association with case expressions in pattern matching. First, the compiler automatically converts the constructor arguments into immutable fields (vals). The val keyword is optional. If you want mutable fields, use the var keyword. So, our constructor argument lists are now shorter. Second, the compiler automatically implements equals, hashCode, and toString methods to the class, which use the fields specified as constructor arguments. So, we no longer need our own toString() methods. Finally, also, the body of Person class becomes empty because there are no methods that we need to define! Print Page Previous Next Advertisements ”;

Scala – Loop Statements

Scala – Loop Statements ”; Previous Next This chapter takes you through the loop control structures in Scala programming languages. There may be a situation, when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages − Flow Chart Scala programming language provides the following types of loops to handle looping requirements. Click the following links in the table to check their detail. Sr.No Loop Type & Description 1 while loop Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. 2 do-while loop Like a while statement, except that it tests the condition at the end of the loop body. 3 for loop Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. Loop Control Statements Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. As such Scala does not support break or continue statement like Java does but starting from Scala version 2.8, there is a way to break the loops. Click the following links to check the detail. Sr.No Control Statement & Description 1 break statement Terminates the loop statement and transfers execution to the statement immediately following the loop. The infinite Loop A loop becomes an infinite loop if a condition never becomes false. If you are using Scala, the while loop is the best way to implement infinite loop. The following program implements infinite loop. Example object Demo { def main(args: Array[String]) { var a = 10; // An infinite loop. while( true ){ println( “Value of a: ” &plus; a ); } } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output If you will execute above code, it will go in infinite loop which you can terminate by pressing Ctrl &plus; C keys. Value of a: 10 Value of a: 10 Value of a: 10 Value of a: 10 ……………. Print Page Previous Next Advertisements ”;

Scala – Environment Setup

Scala – Environment Setup ”; Previous Next Scala can be installed on any UNIX flavored or Windows based system. Before you start installing Scala on your machine, you must have Java 1.8 or greater installed on your computer. Follow the steps given below to install Scala. Step 1: Verify Your Java Installation First of all, you need to have Java Software Development Kit (SDK) installed on your system. To verify this, execute any of the following two commands depending on the platform you are working on. If the Java installation has been done properly, then it will display the current version and specification of your Java installation. A sample output is given in the following table. Platform Command Sample Output Windows Open Command Console and type − >java –version Java version “1.8.0_31” Java (TM) SE Run Time Environment (build 1.8.0_31-b31) Java Hotspot (TM) 64-bit Server VM (build 25.31-b07, mixed mode) Linux Open Command terminal and type − $java –version Java version “1.8.0_31” Open JDK Runtime Environment (rhel-2.8.10.4.el6_4-x86_64) Open JDK 64-Bit Server VM (build 25.31-b07, mixed mode) We assume that the readers of this tutorial have Java SDK version 1.8.0_31 installed on their system. In case you do not have Java SDK, download its current version from http://www.oracle.com/technetwork/java/javase/downloads/index.html and install it. Step 2: Set Your Java Environment Set the environment variable JAVA_HOME to point to the base directory location where Java is installed on your machine. For example, Sr.No Platform & Description 1 Windows Set JAVA_HOME to C:ProgramFilesjavajdk1.7.0_60 2 Linux Export JAVA_HOME=/usr/local/java-current Append the full path of Java compiler location to the System Path. Sr.No Platform & Description 1 Windows Append the String “C:Program FilesJavajdk1.7.0_60bin” to the end of the system variable PATH. 2 Linux Export PATH=$PATH:$JAVA_HOME/bin/ Execute the command java -version from the command prompt as explained above. Step 3: Install Scala You can download Scala from http://www.scala-lang.org/downloads. At the time of writing this tutorial, I downloaded ‘scala-2.11.5-installer.jar’. Make sure you have admin privilege to proceed. Now, execute the following command at the command prompt − Platform Command & Output Description Windows >java –jar scala-2.11.5-installer.jar> This command will display an installation wizard, which will guide you to install Scala on your windows machine. During installation, it will ask for license agreement, simply accept it and further it will ask a path where Scala will be installed. I selected default given path “C:Program FilesScala”, you can select a suitable path as per your convenience. Linux Command − $java –jar scala-2.9.0.1-installer.jar Output − Welcome to the installation of Scala 2.9.0.1! The homepage is at − http://Scala-lang.org/ press 1 to continue, 2 to quit, 3 to redisplay 1………………………………………… [ Starting to unpack ] [ Processing package: Software Package Installation (1/1) ] [ Unpacking finished ] [ Console installation done ] During installation, it will ask for license agreement, to accept it type 1 and it will ask a path where Scala will be installed. I entered /usr/local/share, you can select a suitable path as per your convenience. Finally, open a new command prompt and type Scala -version and press Enter. You should see the following − Platform Command Output Windows >scala -version Scala code runner version 2.11.5 — Copyright 2002-2013, LAMP/EPFL Linux $scala -version Scala code runner version 2.9.0.1 – Copyright 2002-2013, LAMP/EPFL Print Page Previous Next Advertisements ”;