在scala中匹配case对象的有效方法

时间:2017-09-18 15:06:11

标签: scala

我希望得到在印度和中国工作的学生和员工

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
}

是否有任何有效的方法可以避免使用collect的重复代码以及我已完成的案例匹配。

1 个答案:

答案 0 :(得分:2)

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
}