Displays Scala’s numeric literals:
Literal | Type | Description |
5 | Int | Unadorned integer literals are Int by default |
0x0f | Int | The “0x” prefix denotes hexadecimal notation |
5l | Long | The “l” suffix denotes a Long type |
5.0 | Double | Unadorned decimal literals are Double by default |
5f | Float | The “f” suffix denotes a Float type |
5d | Double | The “d suffix denotes a Double type |
Integer Literals
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.
A compile-time error occurs if an integer literal number is specified that is outside these ranges, as in the following examples:
scala> val i = 1234567890123
<console>:1: error: integer number too large
val i = 12345678901234567890
^
scala> val i = 1234567890123L
i: Long = 1234567890123
scala> val b: Byte = 128
<console>:19: error: type mismatch;
found : Int(128)
required: Byte
val b: Byte = 128
^
scala> val b: Byte = 127
b: Byte = 127
Floating-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.
Before Scala 2.10, floating-point literals without a digit after the period were allowed, e.g., 3. and 3.e5 . This syntax leads to some ambiguities, where it can be interpreted as the period before a method name.
How should 1.toString be parsed? Is it 1 the Int or 1.0 the Double ? Hence, literals without at least one digit after the period are deprecated in 2.10 and disallowed in 2.11
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
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.
It is a compile-time error if a backslash character in a character or string literal does not start a valid escape sequence.
Here are some examples:
'A'
'\u0041' // 'A' in Unicode
'\n'
'\012' // '\n' in octal
'\t'
The valid escape sequences are shown in below Table
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 ( \ ) |
Note that nonprintable Unicode characters like \u0009 (tab) are not allowed. Use the equivalents like \t . Recall that three Unicode characters were mentioned in above Table as valid replacements for corresponding ASCII sequences, ⇒ for => , → for -> , and ←
for <- .
String Literals
A string literal is a sequence of characters enclosed in double quotes or triples of double quotes, i.e., """...""" .
For string literals in double quotes, the allowed characters are the same as the character literals. However, if a double quote ( " ) character appears in the string, it must be “escaped” with a \ character.
Here are some examples:
"Learn\nScala"
"He exclaimed, \"Scala is great!\""
"First\tSecond"
The string literals bounded by triples of double quotes are also called multiline string literals. These strings can cover several lines; the line feeds will be part of the string. They can include any characters, including one or two double quotes together, but not
three together. They are useful for strings with \ characters that don’t form valid Unicode or escape sequences, like the valid sequences listed in above Table. Regular expressions are
a good example, which use lots of escaped characters with special meanings. Conversely, if escape sequences appear, they aren’t interpreted.
Here are three example strings:
"""Learn\nScala"""
"""He exclaimed, "Scala is great!" """
"""First line\n
Second line\t
Fourth line"""
Note that we had to add a space before the trailing """ in the second example to prevent a parse error. Trying to escape the second " that ends the "Scala is great!" quote, i.e., "Scala is great!\" , doesn’t work.
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 | .
Consider this example:
def hello(name: String) = s"""Welcome!
Hello, $name!
* (Gratuitous Star!!)
|We're glad you're here.
| Have some extra whitespace.""".stripMargin
hello("Learn Scala")
It prints the following:
Welcome!
Hello, Learn Scala!
* (Gratuitous Star!!)
We're glad you're here.
Have some extra whitespace.
Note where leading whitespace is removed and where it isn’t.
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. Symbols are used less often in Scala compared to some other languages, like Ruby and Lisp.
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. So, an expression like '1symbol is invalid.
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(" Learn Scala ") . All the whitespace is preserved.
Function Literals
We’ve seen function literals already, but to recap,
(i: Int, s: String) => s+i
is a function literal of type
Function2[Int,String,String]
( String is returned).
You can even use the literal syntax for a type declaration. The following declarations are equivalent:
val f1: (Int,String) => String = (i, s) => s+i
val f2: Function2[Int,String,String] = (i, s) => s+i
Tuple Literals
How many times have you wanted to return two or more values from a method? In many languages, like Java, you only have a few options, none of which is very appealing.
You could pass in parameters to the method that will be modified for use as the “return” values, which is ugly. (Some languages even use keywords to indicate which parameters are input versus output.) You could declare some small “structural” class that holds the
two or more values, then return an instance of that class.
The Scala library includes TupleN classes (e.g., Tuple2 ), 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 (though this upper bound may
be eliminated eventually in a future version of Scala).
For example, val tup = ("Learn Scala", 2014) defines a Tuple2 instance with String inferred for the first element and Int inferred for the second element. Tuple instances are immutable, first-class values (because they are objects like any custom type you define), so you can assign them to variables, pass them as values, and return them from methods.
You can also use the literal syntax for Tuple type declarations:
val t1: (Int,String) = (1, "two")
val t2: Tuple2[Int,String] = (1, "two")
The following example demonstrates working with tuples:
1. Use the literal syntax to construct a three-element tuple of type Tuple3
val t = ("Hello", 1, 2.3)
println( "Print the whole tuple: " + t )
Output: Print the whole tuple: (Hello,1,2.3)
2. Extract the first element of the tuple (counting from 1, not 0).
println( ""Print the first item: " + t._1 )
Output: Print the first item: Hello
3. Extract the second element of the tuple (counting from 1, not 0).
println( "Print the second item: " + t._2 )
Output: Print the second item: 1
4. Extract the third element of the tuple (counting from 1, not 0).
println( "Print the third item: " + t ._3)
Output: Print the third item: 2.3
5. On the fly declare three values, t1 , t2 , and t3 , that are assigned the three corresponding fields from the tuple.
val (t1, t2, t3) = ("World", '!', 0x22)
println( t1 + ", " + t2 + ", " + t3 )
Output: World, !, 34
6. Use the Tuple3 “factory” method to construct a tuple.
val (t4, t5, t6) = Tuple3("World", '!', 0x22)
println( t4 + ", " + t5 + ", " + t6 )
Output: World, !, 34
The expression t._n retrieves the n th item from tuple t , starting at one, not zero, following historical conventions.
There are several ways to define a two-element tuple, which is sometimes called a pair for short. In addition to the syntax that uses a parenthesized list of values, you can also use the “arrow operator” between two values, as well as special factory methods on the tuple-related classes:
(1, "one")
1 -> "one"
1 → "one" // Using → character instead of ->
Tuple2(1, "one")
The arrow operator is only available for two-element tuples.
Share this article with your friends.
No comments :
Post a Comment