by hythloday · 13y ago · 0 comments
Except that it is a collection, of exactly zero or one elements. I find it pretty disturbing that someone can work with Scala for 6 months, he says, and not realize this.
The Scala docs (http://www.scala-lang.org/api/current/index.html#scala.Optio...) tell you this in the second paragraph.
To be honest, and I'm being a bit snarky here I know, I think you're just fairly ignorant of basic functional programming techniques. That's not a crime, but don't mouth off about functional programming if you know so little about it.
For what it's worth, with your point about pattern matching, yes, pattern matching on an Option is as trivial as an if-else statement. But here's pattern-matching on an Option[List[String]]:
val v: Option[List[String]] = Some(Nil)
v match {
case None => /* List not found or whatever */
case Some(Nil) => /* List is the empty list */
case Some(List("")) => /* List is a 1-length list of the empty string */
case Some(List(a)) => /* List is a 1-length list */
case Some(List(a, b)) => /* List is a 2-length list of strings a and b */
case Some(head :: tail) => /* List is greater than length with a head and a tail*/
}
Hopefully it's a bit more obvious why that's more concise than the equivalent if-else tree would be.Here's how I'd write the slide I complained about the code style of:
params.getParameter("name")
.map(_.strip)
.filter(!_.isEmpty)
.map(_.toUpperCase)
.getOrElse("")
The "tuples are an abomination" slide - it's much more idiomatic to destructure tuples than to address their contents: // someMap.foreach { keyVal => println(keyVal._1 + "=" + keyVal._2) }
for ((key, value) <- someMap) println(key + "=" + value)
And for what it's worth, this kind of for-expression destructuring is pattern matching, so you can do something like: val collection: List[List[String]] = List(List("a", "b", "c"), List("d", "e"))
for (List(one, two) <- collection) println(one, two) // will just print d, e with no errors
I guess I just think that - no offence - you wrote beginner Scala while you were working on your own and didn't really level up. It's totally a valid criticism of the language that this is easy to do, but blaming the language when you're writing idiosyncratic Scala and wondering why it's so hard to figure out what to do seems unproductive.