fork download
  1. abstract class Box[+T] {
  2. def withFilter[A](p: T => Boolean) = if (isDefined && p(value)) {
  3. println("Box.withFilter")
  4. Full(value)
  5. } else Empty
  6.  
  7. def foreach(act: T => Unit) = if (isDefined) {
  8. println("Box.foreach")
  9. act(value)
  10. }
  11.  
  12. val isDefined: Boolean
  13. def value: T
  14. }
  15. case object Empty extends Box[Nothing] {
  16. override val isDefined = false
  17. override def value = throw new RuntimeException("Empty box")
  18. }
  19. case class Full[T](item: T) extends Box[T] {
  20. override val isDefined = true
  21. override val value = item
  22. }
  23.  
  24. object Main extends App {
  25. val empty = Empty
  26. val full = Full("Surprise")
  27.  
  28. for (x <- empty) println("Empty :[")
  29.  
  30. for {
  31. x <- full
  32. if x startsWith "Sur"
  33. y <- Full(x.reverse)
  34. } println(y)
  35. }
Success #stdin #stdout 0.3s 247488KB
stdin
Standard input is empty
stdout
Box.withFilter
Box.foreach
Box.foreach
esirpruS