fork download
  1. import scala.util.control.Exception.catching
  2.  
  3. object FilterFunctionCompositionAbstractSingletonProxyFactoryBean {
  4. type YobaKostyl = PartialFunction[AnyRef, Option[AnyRef]]
  5.  
  6. def and(f: YobaKostyl*) = f.reduce((f1, f2) ⇒ f1.andThen(_.flatMap(f2)))
  7. def or(obj: AnyRef, f: YobaKostyl*) = f.reduce((f1, f2) ⇒ f1.andThen(_.orElse(f2(obj))))
  8. }
  9.  
  10. object FieldFilterFunctionAbstractSingletonProxyFactoryBean {
  11. import FilterFunctionCompositionAbstractSingletonProxyFactoryBean.YobaKostyl
  12.  
  13. def fieldFilterFunction(name: String)(f: Option[AnyRef] ⇒ Option[AnyRef]): YobaKostyl = {
  14. case obj ⇒
  15. catching(classOf[NoSuchFieldException]).either(obj.getClass.getDeclaredField(name)) match {
  16. case Left(exc)
  17. None
  18. case Right(field)
  19. field.setAccessible(true)
  20. f(Some(field.get(obj))).map(_ ⇒ obj)
  21. }
  22. }
  23. }
  24.  
  25. object TestObjectsAbstractSingletonProxyFactoryBean {
  26. case class A1(yoba: String, petushok: String = "kukareku")
  27. case class A2(peka: Int, list: Seq[String] = Nil)
  28. }
  29.  
  30. object FilterFunctionAbstractSingletonProxyFactoryBean {
  31. import FieldFilterFunctionAbstractSingletonProxyFactoryBean._
  32. import FilterFunctionCompositionAbstractSingletonProxyFactoryBean.YobaKostyl
  33.  
  34. def hasField(name: String): YobaKostyl =
  35. fieldFilterFunction(name)(f ⇒ f)
  36.  
  37. def hasFieldValue[T](name: String, value: T): YobaKostyl =
  38. fieldFilterFunction(name)(_.filter(value ==))
  39.  
  40. def hasListValue[T](name: String, value: T): YobaKostyl =
  41. fieldFilterFunction(name)(_.collect { case list: Iterable[_] ⇒ list }.filter(_.exists(value ==)))
  42. }
  43.  
  44. object Main extends App {
  45. import FilterFunctionAbstractSingletonProxyFactoryBean._
  46. import FilterFunctionCompositionAbstractSingletonProxyFactoryBean._
  47. import TestObjectsAbstractSingletonProxyFactoryBean._
  48.  
  49. val data = Vector(A1("123"), A2(321, Vector("PODI", "PODMOJSA", "MANYA")), A1("ALLOU", "ko-ko-ko"), A2(900))
  50.  
  51. Iterator.continually(readLine()).takeWhile(null ne).foreach(f ⇒ {
  52. println(data.flatMap(yoba ⇒ hasListValue("list", f)(yoba)).mkString(","))
  53. })
  54. }
  55.  
Success #stdin #stdout 0.4s 382208KB
stdin
MANYA
stdout
A2(321,Vector(PODI, PODMOJSA, MANYA))