Efficient way to match case object in scala

2019-08-17 03:22发布

问题:

I want to get Student and employee who works in country India and china

object Countries {
  sealed trait Country {def name: String}
  case object FRANCE extends Country {val name = "FRANCE"}
  case object INDIA extends Country {val name = "INDIA"}
  case object CHINA extends Country {val name = "CHINA"}
  val list = Seq(FRANCE, INDIA, CHINA)
}

def getCountry: Option[Countries.Country] ={
  //some DB call to return country based on some parameters .I assume INDIA here
  Option(Countries.INDIA)
}

case class Student(name: String, id: Symbol = Symbol("Id"))

def getStudentName(name: Option[String]): Option[Student]={
  val std = name
    .filterNot(_.isEmpty)
    .map(Student(_))

  getCountry.collect {
    case Countries.INDIA => std
    case Countries.CHINA => std
  }.flatten              
}

case class Emp(id: Int)

def getEmp(id: Option[String]): Option[Emp] = {
  val emp = id.flatMap(_ => Option(Emp(id.get.toInt)))
  getCountry.collect {
    case Countries.INDIA => emp
    case Countries.CHINA => emp
  }.flatten
}

Is there any efficient way to avoid the repeated code using collect and case matching I have done .

回答1:

def ifCountry[T](result: => Option[T], countries: Country*) = getCountry
  .filter(countries.toSet)
  .flatMap(_ => result)


def getStudentName(name: Option[String]) = ifCountry(
   name.filterNot(_.isEmpty).map(Student(_)),
   INDIA, CHINA
)

def getEmp(id: Option[String]) = ifCountry(
    id.map(Emp(_)), 
    INDIA, CHINA
}


标签: scala