fork(2) 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, list: Seq[String] = Nil)
  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 hasListValue[T](name: String, value: T): YobaKostyl = {
  28. case obj ⇒
  29. catching(classOf[NoSuchFieldException])
  30. .either(obj.getClass.getDeclaredField(name)) match {
  31. case Left(exc)
  32. None
  33. case Right(field)
  34. field.setAccessible(true)
  35. Some(field.get(obj)).collect {
  36. case list: Iterable[_] ⇒ list
  37. }.filter(_.exists(value ==)).map(_ ⇒ obj)
  38. }
  39. }
  40.  
  41. def and(f: YobaKostyl*) = f.reduce((f1, f2) ⇒ f1.andThen(_.flatMap(f2)))
  42. def or(obj: AnyRef, f: YobaKostyl*) = f.reduce((f1, f2) ⇒ f1.andThen(_.orElse(f2(obj))))
  43.  
  44.  
  45. val data = Vector(A1("123"), A2(321, Vector("PODI", "PODMOJSA", "MANYA")), A1("ALLOU", "ko-ko-ko"), A2(900))
  46.  
  47. Iterator.continually(readLine()).takeWhile(null ne).foreach(f ⇒ {
  48. println(data.flatMap(yoba ⇒ hasListValue("list", f)(yoba)).mkString(","))
  49. })
  50. }
  51.  
Success #stdin #stdout 0.4s 382144KB
stdin
MANYA
stdout
A2(321,Vector(PODI, PODMOJSA, MANYA))