To get the actual value if the method succeeds, or use a default value if the method fails, use getOrElse:īecause an Option is a collection with zero or one elements, the foreach method can be used in many situations: As a consumer of a method that returns an Option, there are several good ways to call it and access its result: The toInt example shows how to declare a method that returns an Option. X: Option = None Getting the value from an Option This is what it looks like when it fails and returns a None: This is what toInt looks like in the REPL when it succeeds and returns a Some: Here’s another way to write the same function:ĭef toInt(s: String): Option = allCatch.opt(s.toInt)Īlthough this is a simple function, it shows the common pattern, as well as the syntax.įor a more complicated example, see the readTextFile example in Recipe 20.5. It takes a String as input and returns a Some if the String is successfully converted to an Int, otherwise it returns a None: The toInt method used in this book shows how to return an Option from a method. Using Either/Left/Right when you need the error message (pre-Scala 2.10).Using Try/Success/Failure when you need the error message (Scala 2.10 and newer).This recipe adds these additional solutions: See that recipe for examples of how to use an Option in those situations. Converting null results from other code (such as Java code) into an Option.Using Option to initialize class fields (instead of using null). Using Option in method and constructor parameters.That recipe shows how to use Option instead of null in the following situations: There is some overlap between this recipe and the previous recipe, “Eliminate null Values from Your Code”. Or, if you’re interested in a problem (exception) that occurred while processing code, you may want to return Try/Success/Failure from a method instead of Option/Some/None. This is Recipe 20.6, “Scala best practice: How to use the Option/Some/None pattern.” Problemįor a variety of reasons, including removing null values from your Scala code, you want to use what I call the Option/Some/None pattern. This is an excerpt from the 1st Edition of the Scala Cookbook (partially modified for the internet). show more info on classes/objects in repl.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |