Pattern matching using extractor:
When an instance of a class is followed by parentheses using a list of 0 or more parameters, the compiler invokes the applied method on that instance. We can define both objects and classes.
As mentioned above, the purpose of the Unapply method is to extract a particular value from what we are looking for. It operates in the opposite way as apply. An extract object that compares the Unapply method in a matching statement is automatically executed, as follows:
Object Test {
def main (args:array[string]) {
Val x = Test (5)
println (x)
Match X
{
Case Test (num) => println (x+ "are 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
}
Let's compile and run the above program, which will produce the following results:
C:/>scalac Test.scala
C:/>scala Test
10
Bigger two times than 5
C:/>
Scala opens files using Java objects and java.io.File that can be used to read and write files in Scala programming. Here is an example of writing to a file:
Import Java.io._
Object Test {
def main (args:array[string]) {
Val writer = new PrintWriter (New File ("Test.txt"))
Writer.write ("Hello Scala")
Writer.close ()
}
}
When the above code is compiled and executed, it creates a file with "Hello Scala" content.
C:/>scalac Test.scala
C:/>scala Test
C:/>
To read a line from the screen:
Sometimes you need to read user input from the screen, and then do some further processing. The following example shows how to read input from the screen:
Object Test {
def main (args:array[string]) {
Print ("Please enter your input:")
Val line = Console.ReadLine
println ("Hi, you just typed:" + line)
}
}
When the above code is compiled and executed, it prompts for the content and continues until the ENTER key is pressed.
C:/>scalac Test.scala
C:/>scala Test
Scala Test
Please enter your Input:scala are great
Just Typed:scala is great
C:/>
Read the contents of the file:
Reading from a file is very simple. You can use Scala's source class and its companion object to read files. Here's an example of how these show how to read from a previous "test.txt" file:
Import Scala.io.Source
Object Test {
def main (args:array[string]) {
println ("Following is the content read:")
}
}
}
When the code above is compiled and executed, it reads the Test.txt file and displays the contents on the screen:
C:/>scalac Test.scala
C:/>scala Test
Scala Test
Following is the content read:
Hello Scala
C:/>
from:http://www.yiibai.com/scala/scala_basic_syntax.html