代码之家  ›  专栏  ›  技术社区  ›  coder25

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

  •  0
  • coder25  · 技术社区  · 8 年前

    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 回复  |  直到 8 年前
        1
  •  2
  •   Dima    8 年前
    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
    }
    
    推荐文章