Literal Values

本文详细介绍了Scala语言中各种类型的字面量,包括整数、浮点数、布尔值、字符、字符串、符号及元组等,并提供了丰富的示例说明它们的使用方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. Integer Literals

Integer literals can be expressed in decimal, hexadecimal, or octal.

You indicate a negative number by prefixing the literal with a sign.

For Long literals, it is necessary to append the L or l character at the end of the literal, unless you are assigning the value to a variable declared to be Long. Otherwise, Int is inferred.

Ranges of allowed values for integer literals (boundaries are inclusive)

Target typeMinimum (inclusive)Maximum (inclusive)
Long 263 2631
Int 231 2311
Short 215 2151
Char 0 2161
Byte 27 271

2. Float-Point Literals

Floating-point literals are expressions with an optional minus sign, zero or more digits, followed by a period (.), followed by one or more digits. For Float literals, append the F or f character at the end of the literal. Otherwise, a Double is assumed. You can optionally append a D or d for a Double.

Floating-point literals can be expressed with or without exponentials. The format of the exponential part is e or E, followed by an optional + or , followed by one or more digits.

Here are some example floating-point literals, where Double is inferred unless the declared variable is Float or an f or F suffix is used:

.14
3.14
3.14f
3.14F
3.14d
3.14D
3e5
3E5
3.14e+5
3.14e-5
3.14e-5
3.14e-5f
3.14e-5F
3.14e-5d
3.14e-5D

Float consists of all IEEE 754 32-bit, single-precision binary floating-point values.
Double consists of all IEEE 754 64-bit, double-precision binary floating-point values.

3. Boolean Literals

The Boolean literals are true and false. The type of the variable to which they are assigned will be inferred to be Boolean:

scala> val b1 = true
b1: Boolean = true

scala> val b2 = false
b2: Boolean = false

4. Character Literals

A character literal is either a printable Unicode character or an escape sequence, written between single quotes. A character with a Unicode value between 0 and 255 may also be represented by an octal escape, i.e., a backslash (\) followed by a sequence of up to three octal characters.

Here are some examples:

'A'
'\u0041' // 'A' in Unicode
'\n'
'\012' // '\n' in octal
'\t'

Character escape sequences

SequenceMeaning
\bBackspace (BS)
\tHorizontal tab (HT)
\nLine feed (LF)
\fForm feed (FF)
\rCarriage return (CR)
\"Double quote (")
\'Single quote ()
\\Backslash (\)

5. String Literals

A string literal is a sequence of characters enclosed in double quotes or triples of double quotes.

(1) String.stripMargin

When using multiline strings in code, you’ll want to indent the substrings for proper code formatting, yet you probably don’t want that extra whitespace in the actual string output. String.stripMargin solves this problem. It removes all whitespace in the substrings up to and including the first occurrence of a vertical bar, |. If you want some whitespace indentation, put the whitespace you want after the |.
code example

    def hello(name: String) = s"""
 Welcome!
Hello, $name!
 * (Gratuitous Star!!
 |We're glad you're here.
| Have some extra whitespace.""".stripMargin

    println(hello("Programming Scala"))

output

 Welcome!
Hello, Programming Scala!
 * (Gratuitous Star!!
We're glad you're here.
 Have some extra whitespace.

If you want to use a different leading character than |, use the overloaded version of stripMargin that takes a Char (character) argument.

(2) stripPrefix and stripSuffix

If the whole string has a prefix or suffix you want to remove (but not on individual lines), there are corresponding stripPrefix and stripSuffix methods:

code example

s"""xxxGoodbye,yyy
xxxCome again!yyy""".stripPrefix("xxx").stripSuffix("yyy")

output

Goodbye,yyy
xxxCome again!

6. Symbol Literals

Scala supports symbols, which are interned strings, meaning that two symbols with the same “name” (i.e., the same character sequence) will actually refer to the same object in memory.

A symbol literal is a single quote ('), followed by one or more digits, letters, or underscores (“_”), except the first character can’t be a digit.

A symbol literal 'id is a shorthand for the expression scala.Symbol("id"). If you want to create a symbol that contains whitespace, use Symbol.apply, e.g., Symbol(" Programming Scala "). All the whitespace is preserved.

7. Function Literals

8. Tuple Literals

The Scala library includes TupleN classes (e.g., Tuple2,Tuple3), for grouping N items, with the literal syntax of a comma-separated list of the items inside parentheses. There are separate TupleN classes for N between 1 and 22, inclusive.

(1) Define

There are several ways to define a two-element tuple, which is sometimes called a pair for short.

(1, "one")
1 -> "one"
1"one" // Using → character instead of ->
Tuple2(1, "one")

(2) Index

scala> val tuple = (1, 2)
tuple: (Int, Int) = (1,2)

scala> tuple._1
res1: Int = 1

scala> tuple._2
res2: Int = 2

scala> tuple._0
<console>:13: error: value _0 is not a member of (Int, Int)
       tuple._0
             ^

The expression tuple._n retrieves the nth item from tuple, starting at one, not zero, following historical conventions.


Ref

《Programming Scala》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值