Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Good programmer big data tutorial sample class of Scala series _ Option_ partial function

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/03 Report--

A good programmer big data tutorial Scala series sample class_Option_partial function, in Scala Option type sample class is used to represent values that may or may not exist (Option subclasses are Some and None). Some wraps a value, 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 enclosed in braces without a match 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 input pattern matching.

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"))

//MatchError thrown

println(f("three"))

}

}String INTERPOLATION(optional)

Purpose: Processing String Type:

s: string interpolation

f: Interpolate and format output

raw: output without any transformation of the string

After Scala 2.10.0, a new mechanism for creating strings was introduced, namely String Interpolation. It allows users to embed references to variables directly in strings.

val name="James"

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

A string interpolation can also be placed in an expression, 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 string contents:

scala> s"a\nb"

res0: String =

a

b

scala> raw"a\nb"

res1: String = a\nb

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report