fork(1) download
  1. import scala.util.control.Exception.catching
  2.  
  3. object Main extends App {
  4. case class A1(yoba: String, petushok: String = "kukareku")
  5. case class A2(peka: Int)
  6.  
  7. type YobaKostyl = PartialFunction[AnyRef, Option[AnyRef]]
  8.  
  9. def hasField(name: String): YobaKostyl = {
  10. case obj ⇒
  11. catching(classOf[NoSuchFieldException])
  12. .opt(obj.getClass.getDeclaredField(name)).map(_ ⇒ obj)
  13. }
  14.  
  15. def hasFieldValue[T](name: String, value: T): YobaKostyl = {
  16. case obj ⇒
  17. catching(classOf[NoSuchFieldException])
  18. .either(obj.getClass.getDeclaredField(name)) match {
  19. case Left(exc)
  20. None
  21. case Right(field)
  22. field.setAccessible(true)
  23. Some(field.get(obj)).filter(value ==).map(_ ⇒ obj)
  24. }
  25. }
  26.  
  27. def and(f: YobaKostyl*) = f.reduce((f1, f2) ⇒ f1.andThen(_.flatMap(f2)))
  28. def or(obj: AnyRef, f: YobaKostyl*) = f.reduce((f1, f2) ⇒ f1.andThen(_.orElse(f2(obj))))
  29.  
  30.  
  31. val data = Vector(A1("123"), A2(321), A1("ALLOU", "ko-ko-ko"), A2(900))
  32.  
  33. data.flatMap { obj ⇒
  34. or(obj, and(hasField("yoba"), hasFieldValue("petushok", "ko-ko-ko")), hasFieldValue("peka", 900))(obj)
  35. }.foreach(println)
  36. }
  37.  
Success #stdin #stdout 0.41s 382144KB
stdin
Standard input is empty
stdout
A1(ALLOU,ko-ko-ko)
A2(900)