progs/lecture1.scala
changeset 316 8b57dd326a91
parent 314 21b52310bd8b
child 329 8a34b2ebc8cc
equal deleted inserted replaced
315:7ea440e1ffbb 316:8b57dd326a91
   458   println(cnt)
   458   println(cnt)
   459 }
   459 }
   460 
   460 
   461 test()
   461 test()
   462 
   462 
   463 // Option type
       
   464 //=============
       
   465 
       
   466 //in Java if something unusually happens, you return null or something
       
   467 //
       
   468 //in Scala you use Options instead
       
   469 //   - if the value is present, you use Some(value)
       
   470 //   - if no value is present, you use None
       
   471 
       
   472 
       
   473 List(7,2,3,4,5,6).find(_ < 4)
       
   474 List(5,6,7,8,9).find(_ < 4)
       
   475 
       
   476 
       
   477 
       
   478 // error handling with Options (no exceptions)
       
   479 //
       
   480 //  Try(something).getOrElse(what_to_do_in_case_of_an_exception)
       
   481 //
       
   482 import scala.util._
       
   483 import io.Source
       
   484 
       
   485 val my_url = "https://nms.kcl.ac.uk/christian.urban/"
       
   486 
       
   487 Source.fromURL(my_url).mkString
       
   488 
       
   489 Try(Source.fromURL(my_url).mkString).getOrElse("")
       
   490 
       
   491 Try(Some(Source.fromURL(my_url).mkString)).getOrElse(None)
       
   492 
       
   493 
       
   494 // the same for files
       
   495 Try(Some(Source.fromFile("text.txt").mkString)).getOrElse(None)
       
   496 
       
   497 
       
   498 
       
   499 // how to implement a function for reading something from files...
       
   500 
       
   501 def get_contents(name: String) : List[String] = 
       
   502   Source.fromFile(name).getLines.toList
       
   503 
       
   504 get_contents("test.txt")
       
   505 
       
   506 // slightly better - return Nil
       
   507 def get_contents(name: String) : List[String] = 
       
   508   Try(Source.fromFile(name).getLines.toList).getOrElse(List())
       
   509 
       
   510 get_contents("text.txt")
       
   511 
       
   512 // much better - you record in the type that things can go wrong 
       
   513 def get_contents(name: String) : Option[List[String]] = 
       
   514   Try(Some(Source.fromFile(name).getLines.toList)).getOrElse(None)
       
   515 
       
   516 get_contents("text.txt")
       
   517 get_contents("test.txt")
       
   518 
       
   519 
   463 
   520 
   464 
   521 
   465 
   522 // Further Information
   466 // Further Information
   523 //=====================
   467 //=====================