| 1 | <h2>Comments</h2> |
| 2 | <pre><code>// Single line comment |
| 3 | /* Mutli-line |
| 4 | comment */</code></pre> |
| 5 | |
| 6 | <h2>Strings and characters</h2> |
| 7 | <pre><code>'a' |
| 8 | "foo bar baz" |
| 9 | """Multi-line |
| 10 | string"""</code></pre> |
| 11 | |
| 12 | <h2>Numbers</h2> |
| 13 | <pre><code>0 |
| 14 | 21 |
| 15 | 0xFFFFFFFF |
| 16 | -42L |
| 17 | 0.0 |
| 18 | 1e30f |
| 19 | 3.14159f |
| 20 | 1.0e-100 |
| 21 | .1 |
| 22 | </code></pre> |
| 23 | |
| 24 | <h2>Symbols</h2> |
| 25 | <pre><code>'x |
| 26 | 'identifier</code></pre> |
| 27 | |
| 28 | <h2>Full example</h2> |
| 29 | <pre><code>// Contributed by John Williams |
| 30 | package examples |
| 31 | |
| 32 | object lazyLib { |
| 33 | |
| 34 | /** Delay the evaluation of an expression until it is needed. */ |
| 35 | def delay[A](value: => A): Susp[A] = new SuspImpl[A](value) |
| 36 | |
| 37 | /** Get the value of a delayed expression. */ |
| 38 | implicit def force[A](s: Susp[A]): A = s() |
| 39 | |
| 40 | /** |
| 41 | * Data type of suspended computations. (The name froms from ML.) |
| 42 | */ |
| 43 | abstract class Susp[+A] extends Function0[A] |
| 44 | |
| 45 | /** |
| 46 | * Implementation of suspended computations, separated from the |
| 47 | * abstract class so that the type parameter can be invariant. |
| 48 | */ |
| 49 | class SuspImpl[A](lazyValue: => A) extends Susp[A] { |
| 50 | private var maybeValue: Option[A] = None |
| 51 | |
| 52 | override def apply() = maybeValue match { |
| 53 | case None => |
| 54 | val value = lazyValue |
| 55 | maybeValue = Some(value) |
| 56 | value |
| 57 | case Some(value) => |
| 58 | value |
| 59 | } |
| 60 | |
| 61 | override def toString() = maybeValue match { |
| 62 | case None => "Susp(?)" |
| 63 | case Some(value) => "Susp(" + value + ")" |
| 64 | } |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | object lazyEvaluation { |
| 69 | import lazyLib._ |
| 70 | |
| 71 | def main(args: Array[String]) = { |
| 72 | val s: Susp[Int] = delay { println("evaluating..."); 3 } |
| 73 | |
| 74 | println("s = " + s) // show that s is unevaluated |
| 75 | println("s() = " + s()) // evaluate s |
| 76 | println("s = " + s) // show that the value is saved |
| 77 | println("2 + s = " + (2 + s)) // implicit call to force() |
| 78 | |
| 79 | val sl = delay { Some(3) } |
| 80 | val sl1: Susp[Some[Int]] = sl |
| 81 | val sl2: Susp[Option[Int]] = sl1 // the type is covariant |
| 82 | |
| 83 | println("sl2 = " + sl2) |
| 84 | println("sl2() = " + sl2()) |
| 85 | println("sl2 = " + sl2) |
| 86 | } |
| 87 | }</code></pre> |