YouTip LogoYouTip

Scala Options

Image 1: Scala Collection Scala Collections\n\nThe Scala Option type is used to indicate that a value is optional (has a value or has no value).\n\nOption is a container for an optional value of type T: If the value exists, Option is a Some, and if it does not exist, Option is the object None.\n\nLet's look at a piece of code:\n\n// Although Scala does not require defining the variable type, for clarity, I still\n\n// explicitly defined it\n\nval myMap: Map[String, String]= Map("key1" ->"value")\n\nval value1: Option= myMap.get("key1")\n\nval value2: Option= myMap.get("key2")\n\nprintln(value1)// Some("value1")\n\n println(value2)// None\n\nIn the above code, myMap is a hash map where the Key type is String and the Value type is String, but the difference is that its get() method returns a type called Option.\n\nScala uses Option to tell you: "I will try to return a String, but there might not be a String to give you."\n\nThere is no key2 data in myMap, so the get() method returns None.\n\nOption has two subclasses, one is Some, and the other is None. When it returns Some, it means this function successfully gave you a String, and you can get that String through the get() function. If it returns None, it means there is no string to give you.\n\nAnother example:\n\n## Instance\n\nobject Test {\n\ndef main(args: Array){\n\nval sites = Map("tutorial" ->"example.com", "google" ->"www.google.com")\n\nprintln("sites.get( "tutorial" ) : " + sites.get("tutorial"))// Some(example.com)\n\n println("sites.get( "baidu" ) : " + sites.get("baidu"))// None\n\n}\n\n}\n\nExecuting the above code, the output result is:\n\n$ scalac Test.scala $ scala Test sites.get( "tutorial" ) : Some(example.com) sites.get( "baidu" ) : None\nYou can also use pattern matching to output matching values. The example is as follows:\n\n## Instance\n\nobject Test {\n\ndef main(args: Array){\n\nval sites = Map("tutorial" ->"example.com", "google" ->"www.google.com")\n\nprintln("show(sites.get( "tutorial")) : " + \n\n show(sites.get("tutorial")))\n\n println("show(sites.get( "baidu")) : " + \n\n show(sites.get("baidu")))\n\n}\n\ndef show(x: Option)= x match{\n\ncase Some(s)=> s\n\ncase None =>"?"\n\n}\n\n}\n\nExecuting the above code, the output result is:\n\n$ scalac Test.scala $ scala Test show(sites.get( "tutorial")) : example.com show(sites.get( "baidu")) : ?\n\n* * *\n\n## getOrElse() Method\n\nYou can use the getOrElse() method to get an existing element in the tuple or use its default value. The example is as follows:\n\n## Instance\n\nobject Test {\n\ndef main(args: Array){\n\nval a:Option= Some(5)\n\nval b:Option= None\n\nprintln("a.getOrElse(0): " + a.getOrElse(0))\n\n println("b.getOrElse(10): " + b.getOrElse(10))\n\n}\n\n}\n\nExecuting the above code, the output result is:\n\n$ scalac Test.scala $ scala Test a.getOrElse(0): 5 b.getOrElse(10): 10\n\n* * *\n\n## isEmpty() Method\n\nYou can use the isEmpty() method to detect whether the element in the tuple is None. The example is as follows:\n\n## Instance\n\nobject Test {\n\ndef main(args: Array){\n\nval a:Option= Some(5)\n\nval b:Option= None\n\nprintln("a.isEmpty: " + a.isEmpty)\n\n println("b.isEmpty: " + b.isEmpty)\n\n}\n\n}\n\nExecuting the above code, the output result is:\n\n$ scalac Test.scala $ scala Test a.isEmpty: false b.isEmpty: true\n\n* * *\n\n## Common Methods of Scala Option\n\nThe following table lists the commonly used methods of Scala Option:\n\n| No. | Method & Description |\n| --- | --- |\n| 1 | **def get: A** Returns the optional value |\n| 2 | **def isEmpty: Boolean** Returns true if the optional value is None, otherwise returns false |\n| 3 | **def productArity: Int** Returns the number of elements, A(x_1, ..., x_k), returns k |\n| 4 | **def productElement(n: Int): Any** Returns the specified optional element, starting from 0. i.e., A(x_1, ..., x_k), returns x_(n+1), 0 < n Boolean): Boolean** Returns true if an element satisfying the specified condition exists in the option and is not None, otherwise returns false. |\n| 6 | **def filter(p: (A) => Boolean): Option** Returns Some if the option contains a value and the condition function passed to filter returns true. Otherwise, returns None. |\n| 7 | **def filterNot(p: (A) => Boolean): Option** Returns Some if the option contains a value and the condition function passed to filter returns false. Otherwise, returns None. |\n| 8 | **def flatMap(f: (A) => Option): Option** Returns the result of passing the value to function f if the option contains a value, otherwise returns None |\n| 9 | **def foreach(f: (A) => U): Unit** Passes the value to function f if the option contains a value, otherwise does nothing. |\n| 10 | **def getOrElse[B >: A](default: => B): B** Returns the option's value if it contains a value, otherwise returns the set default value. |\n| 11 | **def isDefined: Boolean** Returns true if the optional value is an instance of Some, otherwise returns false. |\n| 12 | **def iterator: Iterator** Returns an iterator for the optional value if it contains one. Returns an empty iterator if the optional value is empty. |\n| 13 | **def map(f: (A) => B): Option** Returns Some containing the result of applying function f to the option's value if it contains a value, otherwise returns None |\n| 14 | **def orElse[B >: A](alternative: => Option): Option** Returns the alternative option if the option is None, otherwise returns the option itself. |\n| 15 | **def orNull** Returns the option's value if it contains a value, otherwise returns null. |\n\nImage 2: Scala Collection Scala Collections
← Scala IteratorsScala Tuples β†’