Scala – Files I/O

Scala – Files I/O ”; Previous Next Scala is open to make use of any Java objects and java.io.File is one of the objects which can be used in Scala programming to read and write files. The following is an example program to writing to a file. Example import java.io._ object Demo { def main(args: Array[String]) { val writer = new PrintWriter(new File(“test.txt” )) writer.write(“Hello Scala”) writer.close() } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo It will create a file named Demo.txt in the current directory, where the program is placed. The following is the content of that file. Output Hello Scala Reading a Line from Command Line Sometime you need to read user input from the screen and then proceed for some further processing. Following example program shows you how to read input from the command line. Example object Demo { def main(args: Array[String]) { print(“Please enter your input : ” ) val line = Console.readLine println(“Thanks, you just typed: ” + line) } } 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 Please enter your input : Scala is great Thanks, you just typed: Scala is great Reading File Content Reading from files is really simple. You can use Scala”s Source class and its companion object to read files. Following is the example which shows you how to read from “Demo.txt” file which we created earlier. Example import scala.io.Source object Demo { def main(args: Array[String]) { println(“Following is the content read:” ) Source.fromFile(“Demo.txt” ).foreach { print } } } 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 Following is the content read: Hello Scala Print Page Previous Next Advertisements ”;

Scala – Exception Handling

Scala – Exception Handling ”; Previous Next Scala”s exceptions work like exceptions in many other languages like Java. Instead of returning a value in the normal way, a method can terminate by throwing an exception. However, Scala doesn”t actually have checked exceptions. When you want to handle exceptions, you use a try{…}catch{…} block like you would in Java except that the catch block uses matching to identify and handle the exceptions. Throwing Exceptions Throwing an exception looks the same as in Java. You create an exception object and then you throw it with the throw keyword as follows. throw new IllegalArgumentException Catching Exceptions Scala allows you to try/catch any exception in a single block and then perform pattern matching against it using case blocks. Try the following example program to handle exception. Example import java.io.FileReader import java.io.FileNotFoundException import java.io.IOException object Demo { def main(args: Array[String]) { try { val f = new FileReader(“input.txt”) } catch { case ex: FileNotFoundException =>{ println(“Missing file exception”) } case ex: IOException => { println(“IO Exception”) } } } } 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 Missing file exception The behavior of this try-catch expression is the same as in other languages with exceptions. The body is executed, and if it throws an exception, each catch clause is tried in turn. The finally Clause You can wrap an expression with a finally clause if you want to cause some code to execute no matter how the expression terminates. Try the following program. Example import java.io.FileReader import java.io.FileNotFoundException import java.io.IOException object Demo { def main(args: Array[String]) { try { val f = new FileReader(“input.txt”) } catch { case ex: FileNotFoundException => { println(“Missing file exception”) } case ex: IOException => { println(“IO Exception”) } } finally { println(“Exiting finally…”) } } } 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 Missing file exception Exiting finally… Print Page Previous Next Advertisements ”;

Scala – Discussion

Discuss Scala ”; Previous Next Scala is a modern multi-paradigm programming language designed to express common programming patterns in a concise, elegant, and type-safe way. Scala has been created by Martin Odersky and he released the first version in 2003. Scala smoothly integrates the features of object-oriented and functional languages. This tutorial explains the basics of Scala in a simple and reader-friendly way. Print Page Previous Next Advertisements ”;

Scala – Arrays

Scala – Arrays ”; Previous Next Scala provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. Instead of declaring individual variables, such as number0, number1, …, and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and …, numbers[99] to represent individual variables. This tutorial introduces how to declare array variables, create arrays, and process arrays using indexed variables. The index of the first element of an array is the number zero and the index of the last element is the total number of elements minus one. Declaring Array Variables To use an array in a program, you must declare a variable to reference the array and you must specify the type of array the variable can reference. The following is the syntax for declaring an array variable. Syntax var z:Array[String] = new Array[String](3) or var z = new Array[String](3) Here, z is declared as an array of Strings that may hold up to three elements. Values can be assigned to individual elements or get access to individual elements, it can be done by using commands like the following − Command z(0) = “Zara”; z(1) = “Nuha”; z(4/2) = “Ayan” Here, the last example shows that in general the index can be any expression that yields a whole number. There is one more way of defining an array − var z = Array(“Zara”, “Nuha”, “Ayan”) Following picture represents an array myList. Here, myList holds ten double values and the indices are from 0 to 9. Processing Arrays When processing array elements, we often use loop contol structures because all of the elements in an array are of the same type and the size of the array is known. Below is an example program of showing how to create, initialize and process arrays − Example object Demo { def main(args: Array[String]) { var myList = Array(1.9, 2.9, 3.4, 3.5) // Print all the array elements for ( x <- myList ) { println( x ) } // Summing all elements var total = 0.0; for ( i <- 0 to (myList.length – 1)) { total &plus;= myList(i); } println(“Total is ” + total); // Finding the largest element var max = myList(0); for ( i <- 1 to (myList.length – 1) ) { if (myList(i) > max) max = myList(i); } println(“Max is ” &plus; max); } } 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 1.9 2.9 3.4 3.5 Total is 11.7 Max is 3.5 Scala does not directly support various array operations and provides various methods to process arrays in any dimension. If you want to use the different methods then it is required to import Array._ package. Multi-Dimensional Arrays There are many situations where you would need to define and use multi-dimensional arrays (i.e., arrays whose elements are arrays). For example, matrices and tables are examples of structures that can be realized as two-dimensional arrays. The following is the example of defining a two-dimensional array − var myMatrix = ofDim[Int](3,3) This is an array that has three elements each being an array of integers that has three elements. Try the following example program to process a multi-dimensional array − Example import Array._ object Demo { def main(args: Array[String]) { var myMatrix = ofDim[Int](3,3) // build a matrix for (i <- 0 to 2) { for ( j <- 0 to 2) { myMatrix(i)(j) = j; } } // Print two dimensional array for (i <- 0 to 2) { for ( j <- 0 to 2) { print(” ” &plus; myMatrix(i)(j)); } println(); } } } 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 0 1 2 0 1 2 0 1 2 Concatenate Arrays Try the following example which makes use of concat() method to concatenate two arrays. You can pass more than one array as arguments to concat() method. Example import Array._ object Demo { def main(args: Array[String]) { var myList1 = Array(1.9, 2.9, 3.4, 3.5) var myList2 = Array(8.9, 7.9, 0.4, 1.5) var myList3 = concat( myList1, myList2) // Print all the array elements for ( x <- myList3 ) { println( x ) } } } 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 1.9 2.9 3.4 3.5 8.9 7.9 0.4 1.5 Create Array with Range Use of range() method to generate an array containing a sequence of increasing integers in a given range. You can use final argument as step to create the sequence; if you do not use final argument, then step would be assumed as 1. Let us take an example of creating an array of range (10, 20, 2): It means creating an array with elements between 10 and 20 and range difference 2. Elements in the array are 10, 12, 14, 16, and 18. Another example: range (10, 20). Here range difference is not given so by default it assumes 1 element. It create an array with the elements in between 10 and 20 with range difference 1. Elements in the array are 10, 11, 12, 13, …, and 19. The following example program shows how to create an array with ranges. Example import Array._ object Demo { def main(args: Array[String]) { var myList1 = range(10, 20, 2) var myList2 = range(10,20) // Print all the array elements for ( x <- myList1 ) { print( ” ” &plus; x ) } println() for ( x <- myList2 ) { print( ” ” &plus; x ) } } } Save the above program in Demo.scala. The following

Scala – Traits

Scala – Traits ”; Previous Next A trait encapsulates method and field definitions, which can then be reused by mixing them into classes. Unlike class inheritance, in which each class must inherit from just one superclass, a class can mix in any number of traits. Traits are used to define object types by specifying the signature of the supported methods. Scala also allows traits to be partially implemented but traits may not have constructor parameters. A trait definition looks just like a class definition except that it uses the keyword trait. The following is the basic example syntax of trait. Syntax trait Equal { def isEqual(x: Any): Boolean def isNotEqual(x: Any): Boolean = !isEqual(x) } This trait consists of two methods isEqual and isNotEqual. Here, we have not given any implementation for isEqual where as another method has its implementation. Child classes extending a trait can give implementation for the un-implemented methods. So a trait is very similar to what we have abstract classes in Java. Let us assume an example of trait Equal contain two methods isEqual() and isNotEqual(). The trait Equal contain one implemented method that is isEqual() so when user defined class Point extends the trait Equal, implementation to isEqual() method in Point class should be provided. Here it is required to know two important method of Scala, which are used in the following example. obj.isInstanceOf [Point] To check Type of obj and Point are same are not. obj.asInstanceOf [Point] means exact casting by taking the object obj type and returns the same obj as Point type. Try the following example program to implement traits. Example trait Equal { def isEqual(x: Any): Boolean def isNotEqual(x: Any): Boolean = !isEqual(x) } class Point(xc: Int, yc: Int) extends Equal { var x: Int = xc var y: Int = yc def isEqual(obj: Any) = obj.isInstanceOf[Point] && obj.asInstanceOf[Point].x == y } object Demo { def main(args: Array[String]) { val p1 = new Point(2, 3) val p2 = new Point(2, 4) val p3 = new Point(3, 3) println(p1.isNotEqual(p2)) println(p1.isNotEqual(p3)) println(p1.isNotEqual(2)) } } 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 true false true Value classes and Universal Traits Value classes are new mechanism in Scala to avoid allocating runtime objects. It contains a primary constructor with exactly one val parameter. It contains only methods (def) not allowed var, val, nested classes, traits, or objects. Value class cannot be extended by another class. This can be possible by extending your value class with AnyVal. The typesafety of custom datatypes without the runtime overhead. Let us take an examples of value classes Weight, Height, Email, Age, etc. For all these examples it is not required to allocate memory in the application. A value class not allowed to extend traits. To permit value classes to extend traits, universal traits are introduced which extends for Any. Example trait Printable extends Any { def print(): Unit = println(this) } class Wrapper(val underlying: Int) extends AnyVal with Printable object Demo { def main(args: Array[String]) { val w = new Wrapper(3) w.print() // actually requires instantiating a Wrapper instance } } 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 It will give you the hash code of Wrapper class. Wrapper@13 When to Use Traits? There is no firm rule, but here are few guidelines to consider − If the behavior will not be reused, then make it a concrete class. It is not reusable behavior after all. If it might be reused in multiple, unrelated classes, make it a trait. Only traits can be mixed into different parts of the class hierarchy. If you want to inherit from it in Java code, use an abstract class. If you plan to distribute it in compiled form, and you expect outside groups to write classes inheriting from it, you might lean towards using an abstract class. If efficiency is very important, lean towards using a class. Print Page Previous Next Advertisements ”;

Scala – Strings

Scala – Strings ”; Previous Next This chapter takes you through the Scala Strings. In Scala, as in Java, a string is an immutable object, that is, an object that cannot be modified. On the other hand, objects that can be modified, like arrays, are called mutable objects. Strings are very useful objects, in the rest of this section, we present important methods of java.lang.String class. Creating a String The following code can be used to create a String − var greeting = “Hello world!”; or var greeting:String = “Hello world!”; Whenever compiler encounters a string literal in the code, it creates a String object with its value, in this case, “Hello world!”. String keyword can also be given in alternate declaration as shown above. Try the following example program. Example object Demo { val greeting: String = “Hello, world!” def main(args: Array[String]) { println( greeting ) } } 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 Hello, world! As mentioned earlier, String class is immutable. String object once created cannot be changed. If there is a necessity to make a lot of modifications to Strings of characters then use String Builder Class available in Scala!. String Length Methods used to obtain information about an object are known as accessor methods. One accessor method that can be used with strings is the length() method, which returns the number of characters contained in the string object. Use the following code segment to find the length of a string − Example object Demo { def main(args: Array[String]) { var palindrome = “Dot saw I was Tod”; var len = palindrome.length(); println( “String Length is : ” &plus; len ); } } 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 String Length is : 17 Concatenating Strings The String class includes a method for concatenating two strings − string1.concat(string2); This returns a new string that is string1 with string2 added to it at the end. You can also use the concat() method with string literals, as in − “My name is “.concat(“Zara”); Strings are more commonly concatenated with the &plus; operator, as in − “Hello,” &plus; ” world” &plus; “!” Which results in − “Hello, world!” The following lines of code to find string length. Example object Demo { def main(args: Array[String]) { var str1 = “Dot saw I was “; var str2 = “Tod”; println(“Dot ” &plus; str1 &plus; str2); } } 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 Dot Dot saw I was Tod Creating Format Strings You have printf() and format() methods to print output with formatted numbers. The String class has an equivalent class method, format(), that returns a String object rather than a PrintStream object. Try the following example program, which makes use of printf() method − Example object Demo { def main(args: Array[String]) { var floatVar = 12.456 var intVar = 2000 var stringVar = “Hello, Scala!” var fs = printf(“The value of the float variable is ” + “%f, while the value of the integer ” + “variable is %d, and the string” + “is %s”, floatVar, intVar, stringVar); println(fs) } } 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 The value of the float variable is 12.456000, while the value of the integer variable is 2000, and the string is Hello, Scala!() String Interpolation String Interpolation is the new way to create Strings in Scala programming language. This feature supports the versions of Scala-2.10 and later. String Interpolation: The mechanism to embed variable references directly in process string literal. There are three types (interpolators) of implementations in String Interpolation. The ‘s’ String Interpolator The literal ‘s’ allows the usage of variable directly in processing a string, when you prepend ‘s’ to it. Any String variable with in a scope that can be used with in a String. The following are the different usages of ‘s’ String interpolator. The following example code snippet for the implementation of ‘s’ interpolator in appending String variable ($name) to a normal String (Hello) in println statement. val name = “James” println(s “Hello, $name”) //output: Hello, James String interpolater can also process arbitrary expressions. The following code snippet for Processing a String (1 + 1) with arbitrary expression (${1 + 1}) using ‘s’ String interpolator. Any arbitrary expression can be embedded in ‘${}’. println(s “1 &plus; 1 = ${1 &plus; 1}”) //output: 1 &plus; 1 = 2 Try the following example program of implementing ‘s’ interpolator. Example object Demo { def main(args: Array[String]) { val name = “James” println(s”Hello, $name”) println(s”1 &plus; 1 = ${1 &plus; 1}”) } } 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 Hello, James 1 &plus; 1 = 2 The ‘ f ’ Interpolator The literal ‘f’ interpolator allows to create a formatted String, similar to printf in C language. While using ‘f’ interpolator, all variable references should be followed by the printf style format specifiers such as %d, %i, %f, etc. Let us take an example of append floating point value (height = 1.9d) and String variable (name = “James”) with normal string. The following code snippet of implementing ‘f’ Interpolator. Here $name%s to print (String variable) James and $height%2.2f to print (floating point value) 1.90. val height = 1.9d val name = “James” println(f”$name%s is $height%2.2f meters tall”) //James is 1.90 meters tall It is type safe (i.e.) the variable reference and following format specifier should match otherwise it is showing error. The ‘ f ’ interpolator makes use of the String format utilities (format specifiers) available in Java. By default means, there is

Scala – Useful Resources

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 ”;

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 = ” &plus; multiplier(1) ) println( “multiplier(2) value = ” &plus; 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 &plus; Adds two operands A &plus; 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 &plus; B will assign value of A &plus; B into C &plus;= Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand C &plus;= A is equivalent to C = C &plus; 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 : ” &plus; apply(“Zara”, “gmail.com”)); println (“Unapply method : ” &plus; unapply(“[email protected]”)); println (“Unapply method : ” &plus; unapply(“Zara Ali”)); } // The injection method (optional) def apply(user: String, domain: String) = { user &plus;”@”&plus; 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&plus;” is bigger two times than “&plus;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 ”;