Saturday, 18 May 2019

Extractors in Scala

Extractors


Scala extractor is an object which has a method called unapply as one of its members. The unapply method matches a value and take it apart. The extractor also defines apply method for building values.
Consider an example of extracting first name and last name that uses space as separator.
object firstName {
  def main(args: Array[String]) {
    println("Apply method uses : " + apply("Simran", "Raj"));
    println("UnApply method uses : " + unapply("Raj Aryan").get);
    println("UnApply method uses : " + unapply("Shankar"));
  }
  def apply(fstname: String, lstname: String) = {
    fstname + " " + lstname
  }
  def unapply(str: String): Option[(String, String)] = {
    val txtunapply = str split " "
    if (txtunapply.length == 2) {
      Some(txtunapply(0), txtunapply(1))
    } else {
      None
    }
  }
}
//Output
Apply method uses : Simran Raj
UnApply method uses : (Raj,Aryan)
UnApply method uses : None

Scala Extractor Pattern Matching
If the instance of the class contains a list of zero or more parameters, compiler calls apply method on that instance. The apply method can be defined for both objects and classes.
case class Employee(name: String, address: Seq[EmpAddress])
case class EmpAddress(city: String, state: String)
object City {
  def unapply(s: Employee): Option[Seq[String]] =
    Some(
      for (c <- s.address)
        yield c.state)
// For each iteration of your for loop, yield generates a value which is remembered by the for loop (behind the //scenes, like a buffer).
}
class StringSeqContains(value: String) {
  def unapply(in: Seq[String]): Boolean =
    in contains value
}
object PatternMatch {
  def main(args: Array[String]) {
    val stud = List(Employee("Umesh", List(EmpAddress("Bihar", "Patna"))),
      Employee("Reena", List(EmpAddress("India", "Delhi"))),
      Employee("Rajiv", List(EmpAddress("Maharastra", "Mumbai"))),
      Employee("Sujit", List(EmpAddress("WestBengal", "Kolkata"))),
      Employee("Sourabh", List(EmpAddress("WestBengal", "Kolkata")))
    )
    val Delhi = new StringSeqContains("Kolkata")
    val Employees = stud collect {
      case Employee @ City(Delhi()) => Employee.name
    }
    println(Employees)
  }
}
//Output
List(Sujit,Sourabh)

No comments:

Post a Comment

Use filter method to filter a Scala collection

Use filter method to filter a Scala collection To use filter on your collection, give it a predicate to filter the collection elements as...