fork download
  1. object Main extends App {
  2. override def main(args: Array[String]) {
  3.  
  4. // We start with creating some examples:
  5. val definedInt: Option[Int] = Some(3)
  6. val undefinedInt: Option[Int] = None
  7.  
  8. def double(i: Int): Option[Int] = Option(2 * i)
  9.  
  10. // Now let's get create String for each number or "empty" if there is no Int:
  11. val definedStr: String =
  12. definedInt.map(_.toString).getOrElse("empty") // "3"
  13. val undefinedStr: String =
  14. undefinedInt.map(_.toString).getOrElse("empty") // "empty"
  15.  
  16. // Let's try to execute some code only if value is not empty:
  17. for (i <- definedInt) {
  18. println(i) // prints "3"
  19. }
  20. for (i <- undefinedInt) {
  21. println(i) // never called
  22. }
  23.  
  24.  
  25. }
  26. }
Success #stdin #stdout 0.36s 322240KB
stdin
Standard input is empty
stdout
3