Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use Scala Option

Shulou Source: shulou.com Published: 2022-06-02 07:23:07 09月16日 Update

This article introduces the relevant knowledge of "how to use Scala Option". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

In Scala, the Option type sample class is used to represent values that may or may not exist (subclasses of Option are Some and None). Some wraps a value, and None means no value.

Object OptionDemo {

Def main (args: Array [String]) {

Val map = Map ("a"-> 1, "b"-> 2)

Val v = map.get ("b") match {

Case Some (I) = > I

Case None = > 0

}

Println (v)

/ / A better way

Val v1 = map.getOrElse ("c", 0)

Println (v1)

}

}

Partial function

A set of case statements that are wrapped without match in curly braces is a partial function, which is an instance of PartialFunction [A, B], where A represents the parameter type and B represents the return type, often used as an input pattern match

Object PartialFunctionDemo {

Def f: PartialFunction [String, Int] = {

Case "one" = > 1

Case "two" = > 2

/ / case _ = >-1

}

Def main (args: Array [String]) {

/ / call f.apply ("one")

Println (f ("one"))

Println (f.isDefinedAt ("three"))

/ / throw MatchError

Println (f ("three"))

}

} String INTERPOLATION (string interpolation) (alternative)

Purpose: dealing with string types:

S: string interpolation

F: interpolate and format the output

Raw: output without any transformation on the string

After Scala 2. 10. 0, a new mechanism for creating strings, String Interpolation. 0, is introduced. It allows the user to embed a reference to a variable directly in a string.

Val name= "James"

Println (s "Hello,$name") / / Hello, James

The position of string interpolation can also be expressed as follows:

Println (s "1 + 1 = ${1 + 1}") / / 1 + 1 = 2

Interpolation f can format strings, similar to printf:

Val height = 1.9d

Val name = "James"

Println (f "$name%s is $height%2.2f meters tall") / / James is 1.90 meters tall

Raw is similar to s, but raw does not convert the contents of the string:

Scala > s "a\ nb"

Res0: String =

A

B

Scala > raw "a\ nb"

Res1: String = a\ nb

That's all for the content of "how to use Scala Option". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Tags: Character string interpolation type content output representative function more format knowledge utility achievement next position parameter variable dilemma subclass instance Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Shulou Technology Xiaomi MariaDB NVidia