Exc10 Scala Option
-
- Erstie
- Beiträge: 18
- Registriert: 21. Mai 2012 15:07
Exc10 Scala Option
Can somebody explain to me why Scala Option is being used (ie in store.get) instead of just returning the actual value? Whats the point of using Scala Option in general?
Re: Exc10 Scala Option
http://blog.danielwellman.com/2008/03/u ... as-op.html can give you a first insight about this.
-
- Erstie
- Beiträge: 18
- Registriert: 21. Mai 2012 15:07
Re: Exc10 Scala Option
Thats what i suspected, but the article was a great starting point for a lot more insight. Thanks!
-
- Nerd
- Beiträge: 681
- Registriert: 26. Okt 2006 14:04
- Kontaktdaten:
Re: Exc10 Scala Option
Note that the Option type implements map and foreach that are executed only if the Option is-a Some. Using that, you can get rid of a lot if if-else/match code. Also, if you have Lists of Option, you can use flatten to remove all appearances of None and get all Somes.
Here are the examples:
As you see at the val definition, a light "pitfall" is that the type inference is quite tight. If you initialize a variable with None, it will not infer Option[YourType], but None, because your type cannot be infered from the context; you will have to declare it explicitely.
Here are the examples:
Code: Alles auswählen
scala> val some = Some(3)
some: Some[Int] = Some(3)
scala> val none: Option[Int] = None
none: Option[Int] = None
scala> some.foreach(println)
3
scala> none.foreach(println)
scala> some.map(_ * math.Pi)
res2: Option[Double] = Some(9.42477796076938)
scala> none.map(_ * math.Pi)
res3: Option[Double] = None
scala> none.map(_ * math.Pi).getOrElse(1)
res4: AnyVal = 1
scala> List(Some(1), Some(2), None, Some(4)).flatten
res5: List[Int] = List(1, 2, 4)