Literals is special syntax for constructing values. They work for anything from numbers to anonymous functions.
All strings accept UTF-8 characters and are natively Unicode. They are enclosed in either single (') or double quotes ("). They cannot contain the enclosing character, newline or backslash, except through the following escape sequences:
Example |
Description |
|
Carriage return. |
|
Newline (line feed). |
|
Tabulator. |
|
Single quote. |
|
Double quote. |
|
Backslash. |
|
Unicode point 0000 (16 bit) in hexadecimal. |
|
Unicode point 00000000 (32 bit) in hexadecimal. |
Example of escape sequences:
val e = "\u00DC is the first character in \"Über\"" # s is then: Ü is the first character in "Über"
They can also contain variable references \{myVar}
(also supports properties), and these can be formatted as follows:
val f = 3.141593 val d = Date() val s = 'f is \{f|2.3}, d is \{d|YYYY-MM-DD}' # s is then, by the time I wrote this: f is 03.142, d is 2008-05-18
You can implement formatting for your own types by implementing the format(code: String): String
method. See this documentation for existing formatting codes.
Number literals are either Int
, Integer
or Float
.
An integer literal consists of an optional sign, an optional base specification, the digits, and optionally a type.
-127 # Decimal number (with sign) 0x123def # Hexadecimal number (base 16 is 0x) 0b100110 # Binary number (base 2 is 0b) 23082580395376a # An arbitrary precision Integer (indicated by the trailing a)
A floating point number is double precision and consists of an optional sign, one or more digits, a dot, one or more digits and optionally an exponent:
3.141593 # Approximation of Pi +1.025e-2 # Equals 0.01025
The main purpose of Collections is to contain other values.
val l = [1, 2, 3, 4] # The list of four specific numbers val e: Int* = [] # The empty list (note that the type must be known in advance)
val l = [|1| "one" |7| "seven"] # A map from Int to String (1 => "one", 2 => "two") val e: Map[Int, String] = [|] # The empty map (note that the type must be known in advance)
val f = {|a: Int, b: Int| a + b } val g: (Int, Int) -> Int = {|a, b| a + b } val h = { Console.writeLine("Hello!") }
In the example above, f
is the function that takes two Int
and returns the sum of them. g
is the same function, but since the type is known in advance, we need not specify the type of the two parameters. Note that the return type is always inferred. The last function h
has the type Void -> Void
and thus doesn't need a parameter list.
f(2, 3) # Equals 5 h() # Prints "Hello!"