天天看點

Literal Values1. Integer Literals2. Float-Point Literals3. Boolean Literals4. Character Literals5. String Literals6. Symbol Literals7. Function Literals8. Tuple Literals

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 type Minimum (inclusive) Maximum (inclusive)

Long

−263 263−1

Int

−231 231−1

Short

−215 215−1

Char

216−1

Byte

−27 27−1

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:

f
F
d
D





f
F
d
D
           

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

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

Sequence Meaning

\b

Backspace (BS)

\t

Horizontal tab (HT)

\n

Line feed (LF)

\f

Form feed (FF)

\r

Carriage 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.

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

(2) Index

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

scala> tuple._1
res1: Int = 

scala> tuple._2
res2: Int = 

scala> tuple._0
<console>:: 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》