This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class NullExample { | |
public static void main(String[] args) { | |
String s = getString(); | |
if (s != null) { | |
// ... | |
} else { | |
// ... | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object OptionExample { | |
def main(args: Array[String]) { | |
val s: Option[String] = Option(getString()) | |
s match { | |
case Some(s) => // ... | |
case None => // ... | |
} | |
} | |
} |
Besides compile-time distinction between null and non-null instances, options are designed in such a way that they play very nicely with the functional side of Scala. In fact, options are treated as a collection where there is either zero or one element. That means you can do all sorts of interesting things such as:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object OptionFun { | |
def main(args: Array[String]) { | |
val s: Option[String] = Option(getString()) | |
// print it if it's non-null | |
s.foreach(println(_)) | |
// call a method if it's non-null and return the result as an option | |
s.map(_.toUpperCase()) | |
// get the string if it's non-null; empty string otherwise | |
s.getOrElse("") | |
// returns true if it's null or the empty string | |
s.forall(_.isEmpty()) | |
} | |
} |
type-safe nullables ftw. Maybe in Haskell blew my mind
ReplyDeleteHaha yeah. Whoever thought that segfaults and NPEs weren't the only way to program?
ReplyDelete