Scala – Useful Resources ”; Previous Next The following resources contain additional information on Scala. Please use them to get more in-depth knowledge on this topic. Useful Video Courses Scala Programming Course from Scratch 83 Lectures 7 hours Tutorialspoint More Detail Apache Spark with Scala Course – Hands On with Big Data 24 Lectures 1.5 hours Mukund Kumar Mishra More Detail Delta Lake with Apache Spark using Scala 53 Lectures 2 hours Bigdata Engineer More Detail Apache Spark with Scala for Certified Databricks Professional 78 Lectures 5.5 hours Bigdata Engineer More Detail Machine Learning with Apache Spark 3.0 using Scala 71 Lectures 7.5 hours Bigdata Engineer More Detail Scala Programming Language 46 Lectures 4.5 hours Stone River ELearning More Detail Print Page Previous Next Advertisements ”;
Category: Computer Programming
Scala – Closures
Scala – Closures ”; Previous Next A closure is a function, whose return value depends on the value of one or more variables declared outside this function. The following piece of code with anonymous function. val multiplier = (i:Int) => i * 10 Here the only variable used in the function body, i * 10 , is i, which is defined as a parameter to the function. Try the following code − val multiplier = (i:Int) => i * factor There are two free variables in multiplier: i and factor. One of them, i, is a formal parameter to the function. Hence, it is bound to a new value each time multiplier is called. However, factor is not a formal parameter, then what is this? Let us add one more line of code. var factor = 3 val multiplier = (i:Int) => i * factor Now factor has a reference to a variable outside the function but in the enclosing scope. The function references factor and reads its current value each time. If a function has no external references, then it is trivially closed over itself. No external context is required. Try the following example program. Example object Demo { def main(args: Array[String]) { println( “multiplier(1) value = ” + multiplier(1) ) println( “multiplier(2) value = ” + multiplier(2) ) } var factor = 3 val multiplier = (i:Int) => i * factor } 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 multiplier(1) value = 3 multiplier(2) value = 6 Print Page Previous Next Advertisements ”;
Scala – Operators
Scala – Operators ”; Previous Next An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. Scala is rich in built-in operators and provides the following types of operators − Arithmetic Operators Relational Operators Logical Operators Bitwise Operators Assignment Operators This chapter will examine the arithmetic, relational, logical, bitwise, assignment and other operators one by one. Arithmetic Operators The following arithmetic operators are supported by Scala language. For example, let us assume variable A holds 10 and variable B holds 20, then − Show Examples Operator Description Example + Adds two operands A + B will give 30 – Subtracts second operand from the first A – B will give -10 * Multiplies both operands A * B will give 200 / Divides numerator by de-numerator B / A will give 2 % Modulus operator finds the remainder after division of one number by another B % A will give 0 Relational Operators The following relational operators are supported by Scala language. For example let us assume variable A holds 10 and variable B holds 20, then − Show Examples Operator Description Example == Checks if the values of two operands are equal or not, if yes then condition becomes true. (A == B) is not true. != Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. (A != B) is true. > Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (A > B) is not true. < Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (A < B) is true. >= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (A >= B) is not true. <= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (A <= B) is true. Logical Operators The following logical operators are supported by Scala language. For example, assume variable A holds 1 and variable B holds 0, then − Show Examples Operator Description Example && It is called Logical AND operator. If both the operands are non zero then condition becomes true. (A && B) is false. || It is called Logical OR Operator. If any of the two operands is non zero then condition becomes true. (A || B) is true. ! It is called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. !(A && B) is true. Bitwise Operators Bitwise operator works on bits and perform bit by bit operation. The truth tables for &, |, and ^ are as follows − p q p & q p | q p ^ q 0 0 0 0 0 0 1 0 1 1 1 1 1 1 0 1 0 0 1 1 Assume if A = 60; and B = 13; now in binary format they will be as follows − A = 0011 1100 B = 0000 1101 ———————– A&B = 0000 1100 A|B = 0011 1101 A^B = 0011 0001 ~A = 1100 0011 The Bitwise operators supported by Scala language is listed in the following table. Assume variable A holds 60 and variable B holds 13, then − Show Examples Operator Description Example & Binary AND Operator copies a bit to the result if it exists in both operands. (A & B) will give 12, which is 0000 1100 | Binary OR Operator copies a bit if it exists in either operand. (A | B) will give 61, which is 0011 1101 ^ Binary XOR Operator copies the bit if it is set in one operand but not both. (A ^ B) will give 49, which is 0011 0001 ~ Binary Ones Complement Operator is unary and has the effect of ”flipping” bits. (~A ) will give -61, which is 1100 0011 in 2”s complement form due to a signed binary number. << Binary Left Shift Operator. The bit positions of the left operands value is moved left by the number of bits specified by the right operand. A << 2 will give 240, which is 1111 0000 >> Binary Right Shift Operator. The Bit positions of the left operand value is moved right by the number of bits specified by the right operand. A >> 2 will give 15, which is 1111 >>> Shift right zero fill operator. The left operands value is moved right by the number of bits specified by the right operand and shifted values are filled up with zeros. A >>>2 will give 15 which is 0000 1111 Assignment Operators There are following assignment operators supported by Scala language − Show Examples Operator Description Example = Simple assignment operator, Assigns values from right side operands to left side operand C = A + B will assign value of A + B into C += Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand C += A is equivalent to C = C + A -= Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand C -= A is equivalent to C = C – A *= Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand C *= A is equivalent to C = C * A /= Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand C /= A is equivalent to C = C / A %= Modulus AND assignment operator, It takes modulus using two operands
Scala – Extractors
Scala – Extractors ”; Previous Next An extractor in Scala is an object that has a method called unapply as one of its members. The purpose of that unapply method is to match a value and take it apart. Often, the extractor object also defines a dual method apply for building values, but this is not required. Example Let us take an example of object defines both apply and unapply methods. The apply method has the same meaning as always: it turns Test into an object that can be applied to arguments in parentheses in the same way a method is applied. So you can write Test (“Zara”, “gmail.com”) to construct the string “[email protected]”. The unapply method is what turns Test class into an extractor and it reverses the construction process of apply. Where apply takes two strings and forms an email address string out of them, unapply takes an email address and returns potentially two strings: the user and the domain of the address. The unapply must also handle the case where the given string is not an email address. That”s why unapply returns an Option-type over pairs of strings. Its result is either Some (user, domain) if the string str is an email address with the given user and domain parts, or None, if str is not an email address. Here are some examples as follows. Syntax unapply(“[email protected]”) equals Some(“Zara”, “gmail.com”) unapply(“Zara Ali”) equals None Following example program shows an extractor object for email addresses. Example object Demo { def main(args: Array[String]) { println (“Apply method : ” + apply(“Zara”, “gmail.com”)); println (“Unapply method : ” + unapply(“[email protected]”)); println (“Unapply method : ” + unapply(“Zara Ali”)); } // The injection method (optional) def apply(user: String, domain: String) = { user +”@”+ domain } // The extraction method (mandatory) def unapply(str: String): Option[(String, String)] = { val parts = str split “@” if (parts.length == 2){ Some(parts(0), parts(1)) } else { None } } } 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 Apply method : [email protected] Unapply method : Some((Zara,gmail.com)) Unapply method : None Pattern Matching with Extractors When an instance of a class is followed by parentheses with a list of zero or more parameters, the compiler invokes the apply method on that instance. We can define apply both in objects and in classes. As mentioned above, the purpose of the unapply method is to extract a specific value we are looking for. It does the opposite operation apply does. When comparing an extractor object using the match statement the unapply method will be automatically executed. Try the following example program. Example object Demo { def main(args: Array[String]) { val x = Demo(5) println(x) x match { case Demo(num) => println(x+” is bigger two times than “+num) //unapply is invoked case _ => println(“i cannot calculate”) } } def apply(x: Int) = x*2 def unapply(z: Int): Option[Int] = if (z%2==0) Some(z/2) else None } 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 10 10 is bigger two times than 5 Print Page Previous Next Advertisements ”;
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
Ruby – Discussion
Discuss Ruby ”; Previous Next Ruby is a scripting language designed by Yukihiro Matsumoto, also known as Matz. It runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. This tutorial gives a complete understanding on Ruby. Print Page Previous Next Advertisements ”;
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 ”;