Showing posts with label b4005| for loop N yield. Show all posts
Showing posts with label b4005| for loop N yield. Show all posts

Exception Example

scala> :paste
// Entering paste mode (ctrl-D to finish)

// Best Practice : Exceptions are NOT recommended in Scala
// Might need to use when we are dealing with Java APIs
//#Programming Scala:83
//psn > a30 > a50
//Example : Identifying the file size
import scala.io.Source
import scala.util.control.NonFatal
object ReadFile {
  def main(args: Array[String]) = {
    args.foreach{ arg =>
                  println(s"arg -> $arg")
                  countLineSize(arg)  
                }
  }
  
  // Count no of lines in the given File
  def countLineSize(fileName: String) = {
    println("Inside countLineSize()")
    var source: Option[Source] = None
    try {
      source = Some(Source.fromFile(fileName))
      val size = source.get.getLines.size
      println(s"file $fileName has $size lines")
    }catch {
      //*** Instead of using Separate Catch Clause to handle
      //    every exception type, we can use pattern matching
      case NonFatal(x) => println(s"Non fatal exception -> $x")
    }finally {
        // Extract 'Source' from 'Option'
        for (s <- source) {
            println(s"Closing file $fileName...")
            s.close
       }
    }
  }
  
}

// Exiting paste mode, now interpreting.

import scala.io.Source
import scala.util.control.NonFatal
defined module ReadFile

scala>  ReadFile.main(Array("./testfile.txt"))
arg -> ./testfile.txt
Inside countLineSize()
Non fatal exception -> java.io.FileNotFoundException: ./testfile.txt (No such file or directory)

For Comprehension Examples

scala> //#PS:79

scala> //psn > a30 > a40

scala> val subjects = List(  Some("english"), 
     |                       None, 
     |                       Some("physics"), 
     |                       Some("math"),
     |                       None)
subjects: List[Option[String]] = List(Some(english), None, Some(physics), Some(math), None)

scala> // Example 1                       

scala> val filtered = for { 
     |   subjectOption <- subjects
         //***Note here... Exception is not raised when we have None
         //*** Option can be considered as a Special kind of Collection
         //    which can be extracted using 'for comprehension'
     |   subject <- subjectOption 
     | }yield {
     |   subject
     | }
filtered: List[String] = List(english, physics, math)

scala>   
     | // Example 2                     

scala> val filtered = for { 
     |   subjectOption <- subjects
     |   // When subjectOption is None, that value is automatically
     |   // execluded. ***Note here... Exception is not raised when we have
     |   // None
     |   subject <- subjectOption 
     |   if subject == "english" || subject == "math"
     | }yield {
     |   subject
     | }
filtered: List[String] = List(english, math)

scala> 

scala> // Example 3 : Achieves same goal as Example 2, but in a much clean 

scala> //             way

scala> val filtered = for {
     |   // Pattern matching is used here
     |   Some(subject) <- subjects
     |   if subject == "english" || subject == "math"
     | }yield {
     |   subject
     | }
filtered: List[String] = List(english, math)

Data Conversion using : Map, for/yield etc...

scala> // Step 1

scala> val inputList = List(  "data=first data || key1=r1v1 || key2=",
     |                        "data=second data || key1=r2v1 || key2=r2v2",
     |                        "key1=r3v1"
     |                       )
inputList: List[String] = List(data=first data || key1=r1v1 || key2=, data=second data || key1=r2v1 || key2=r2v2, key1=r3v1)

scala> // Step 2

scala> val splitted = inputList.map{ x =>
     |   x.split("\\|\\|")
     |    .map(_.trim)
     | }
splitted: List[Array[String]] = List(Array(data=first data, key1=r1v1, key2=), Array(data=second data, key1=r2v1, key2=r2v2), Array(key1=r3v1))

scala> // Step 3

scala> val filteredList = splitted.map{ x =>
     |   val retval = for { element <- x
     |       val keyNval = element.split("=")
     |       if keyNval.size >= 2
     |     } yield {
     |       val splitted = element.split("=")
     |       // Create Tuple of Key and Value
     |       splitted(0) -> splitted(1)
     |     }
     |   retval
     | }
warning: there were 1 deprecation warning(s); re-run with -deprecation for details
filteredList: List[Array[(String, String)]] = List(Array((data,first data), (key1,r1v1)), Array((data,second data), (key1,r2v1), (key2,r2v2)), Array((key1,r3v1)))

scala> // Step 4

scala> val dnryList = filteredList.map{ x =>
     |   x.toMap
     | }
dnryList: List[scala.collection.immutable.Map[String,String]] = List(Map(data -> first data, key1 -> r1v1), Map(data -> second data, key1 -> r2v1, key2 -> r2v2), Map(key1 -> r3v1))

scala> // Step 5

scala> val filteredDnryList = dnryList.filter{ x =>
     |   if (x.getOrElse("data", ()) != ())
     |     true
     |   else
     |     false
     | }
filteredDnryList: List[scala.collection.immutable.Map[String,String]] = List(Map(data -> first data, key1 -> r1v1), Map(data -> second data, key1 -> r2v1, key2 -> r2v2))

scala> // Step 6

scala> val keyvaluepairs = filteredDnryList.map { x =>
     |   val data = x.getOrElse("data", "")
     |   (data, x)
     | }
keyvaluepairs: List[(String, scala.collection.immutable.Map[String,String])] = List((first data,Map(data -> first data, key1 -> r1v1)), (second data,Map(data -> second data, key1 -> r2v1, key2 -> r2v2)))

scala> // Step 7

scala> val words = keyvaluepairs.flatMap{ x =>
     |   //Underscore (_) is used as a Placeholder indicator
     |   val xsplitted = x._1.split(" ").map(_.trim)
     |   val wordNmeta = for { element <- xsplitted
     |     } yield {
     |       (element, x._2)
     |     }
     |   wordNmeta
     | }
words: List[(String, scala.collection.immutable.Map[String,String])] = List((first,Map(data -> first data, key1 -> r1v1)), (data,Map(data -> first data, key1 -> r1v1)), (second,Map(data -> second data, key1 -> r2v1, key2 -> r2v2)), (data,Map(data -> second data, key1 -> r2v1, key2 -> r2v2)))
c200 > a15