diff -r 7ea440e1ffbb -r 8b57dd326a91 progs/lecture1.scala --- a/progs/lecture1.scala Sat Nov 09 22:04:53 2019 +0000 +++ b/progs/lecture1.scala Mon Nov 11 13:24:12 2019 +0000 @@ -460,62 +460,6 @@ test() -// Option type -//============= - -//in Java if something unusually happens, you return null or something -// -//in Scala you use Options instead -// - if the value is present, you use Some(value) -// - if no value is present, you use None - - -List(7,2,3,4,5,6).find(_ < 4) -List(5,6,7,8,9).find(_ < 4) - - - -// error handling with Options (no exceptions) -// -// Try(something).getOrElse(what_to_do_in_case_of_an_exception) -// -import scala.util._ -import io.Source - -val my_url = "https://nms.kcl.ac.uk/christian.urban/" - -Source.fromURL(my_url).mkString - -Try(Source.fromURL(my_url).mkString).getOrElse("") - -Try(Some(Source.fromURL(my_url).mkString)).getOrElse(None) - - -// the same for files -Try(Some(Source.fromFile("text.txt").mkString)).getOrElse(None) - - - -// how to implement a function for reading something from files... - -def get_contents(name: String) : List[String] = - Source.fromFile(name).getLines.toList - -get_contents("test.txt") - -// slightly better - return Nil -def get_contents(name: String) : List[String] = - Try(Source.fromFile(name).getLines.toList).getOrElse(List()) - -get_contents("text.txt") - -// much better - you record in the type that things can go wrong -def get_contents(name: String) : Option[List[String]] = - Try(Some(Source.fromFile(name).getLines.toList)).getOrElse(None) - -get_contents("text.txt") -get_contents("test.txt") -