I added an intro, a summary, and a few more ideas to the Code Google post. It needs a better name that doesn't just mean "search" to people and also doesn't include trademarked words :).
Safe navigaion in Scala, take 2
OK, revisiting this topic after a very short time, I have a new implementation, again using that interesting anonymous class technique from James Iry's comment: implicit def richOption[T](x : T) = new { def ??[B](f : T => B):B = if (x != null) f(x) else null.asInstanceOf[B] } I changed the operator from "?!" to "??" because that's a lot easier to type and I chose "??" instead of "?" so people wouldn't confuse it with the questi-colon operator from Java and C. It's stand-alone (doesn't depend on Option or anything) and I had to use a cast to get the types to work out properly, but the test case from my last post does work println(p3??(_.bud)??(_.bud)??(_.bud)??(_.name.drop(1))) prints null and println(p3??(_.bud)??(_.bud)??(_.name.drop(1))) prints ubba. For those new to Scala, the expressions in parentheses are anonymous functions because they use "_" as identifiers. (_.bud) expands to (x => x.bud), where Sca...
Comments
Post a Comment