You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
about: Thanks to <a href="http://brenocon.com/">Brendan O'Connor</a>, this cheatsheet aims to be a quick reference of Scala syntactic constructions. Licensed by Brendan O'Connor under a CC-BY-SA 3.0 license.
6
6
---
7
7
8
8
###### Contributed by {{ page.by }}
9
9
10
-
|||
10
+
|note: "this is a lie" means i gave a simplified explanation and left out details which will be covered later||
11
11
| ------ | ------ |
12
-
| <h2id="declarations">declarations</h2> ||
12
+
| <h2id="declarations">Basic declarations</h2> ||
13
13
|`var x = 5`<br>`x = 6`| mutable variable, value can be changed later |
14
14
| <spanclass="label success">Good</span> `val x = 5`<br> <spanclass="label important">Bad</span> `x=6`| immutable, cannot be changed |
15
15
|`var x: Double = 5`| explicit type. if not provided, compiler will pick one (more later) |
@@ -19,13 +19,53 @@ about: Thanks to <a href="http://brenocon.com/">Brendan O'Connor</a>, this cheat
|`def x(foo:String, bar:String):String = return foo+"hello world"+bar`| method declaration with two parameters |
21
21
|`def x:String = {val x = 1;return "hello world"+1}`| multiple statements need {} around the code |
22
-
| `def x = "hello world"`|return keyword and return type declaration are optional. default return value = last value in code block
23
-
|`def x {print("hello world")}`| method without "=" means the method has no return type/return type is void (this is a lie to keep things simple, more later) |
22
+
| `def x = "hello world"`|return keyword and return type declaration are optional, but if a method contains return, the return type *must* be specified explicitly. default return value = last value in code block.
24
23
|`def x = {def y = 7;y}`| nested declarations are possible|
25
24
|`class Foo`| class declaration - nested declaration also possible|
26
25
|`class Foo(var x:String, val y:Int)`| class declaration with 2 public fields, one mutable, one immutable. constructor is automatically generated. only new Foo("1",2) is possible|
27
26
|`class Foo {var x = 5;val y = 6}`|class like above, but with default constructor, only new Foo() is possible|
28
27
|`class Foo {def x = 5}`|class with default constructor and one method|
28
+
|`val x = {class y(val z: String); new y("hello").z}`<br><spanclass="label important">Bad</span>`val foo = new y("does not work outside the block above")`| everything can be nested in anything, but everything can only be accessed in its scope|
|`var func = (i:Int) => i+1`|creates a function and stores it in a variable|
32
+
|`func(5)`|executing the function above|
33
+
|`def func = (i:Int) => i+1`|creates a function each time the method is called and returns that function, not i+1|
34
+
|`lazy val x = expensiveOperation()`|the expensive operation is executed once as soon as the value of x is needed, not before|
35
+
| <h2id="typeinference">Return types and type inference</h2> ||
36
+
|`val x = "hello"`|the compiler always picks the most specific type possible, in this case java.lang.String|
37
+
|`val x:Serializable = "hello"`|you can always specify a more general one|
38
+
|`def x {print("hello world")}`| method without "=" means the method has no return type/return type is void (this is a lie) |
39
+
|`def x:Unit = {...}`<br>`def x() {...}`|leaving out the "=" at a method declaration is the same as specifying "Unit"|
40
+
|`val blocks = {{{{5}}}}`|every block has a return type that is passed back to the next outer block|
41
+
|`val block = if (a) foo else bar`|almost everything is an expression and thus, has a return type. this includes if-else-structures|
42
+
|`def x = if (System.currentTimeMillis() % 2 == 0) Integer.valueOf(1) else java.lang.Double.valueOf(2)`|here, the compiler picks the most specific supertype of both Integer and Double which is java.lang.Number (this is a lie)|
43
+
|`def x(i:Int):Int = if (i==0) 1 else i*x(i-1)`|recursive methods need an explicit return type. fail.|
44
+
|`val func:(Int) => String = (i:Int) => i.toString`|just so you know the syntax of a type of a function :)|
45
+
|`def takesFunction(f:(Int) => String) = f(5)`| method that takes the function above as a parameter and calls it. compiler figures out the return type "string" for you.|
46
+
|`def method(i:Int) = t.toString;val func = method _`|appending an "_" converts any method into a function|
47
+
|`takesFunction(method)`|is also possible, the compiler does the conversion for you in obvious cases|
48
+
| <h2id="collections">Scala Collections</h2> ||
49
+
|`Set(1,2,3), Buffer(1,2,3), ArrayBuffer(1,2,3), ListBuffer(1,2,3), List(1,2,3), Array(1,2,3),Vector(1,2,3), Map(1 -> "a", 2 -> "b")`|simple collection creations. scala has mutable and immutable collections.|
50
+
|`mutableColl += elem`|add element to a collection|
51
+
|`mutableColl -= elem`|remove element|
52
+
|`mutableColl ++= elems`|add elements|
53
+
|`mutableColl --= elems`|remove elements|
54
+
|`elem +=: mutableColl`|adds element at the beginning of a collection|
55
+
|`mutableColl :+= elem`|adds element at the end of a collection|
56
+
|`mutableColl(0)`|read access by index|
57
+
|`mutableColl(0) = 1`|write access by index|
58
+
|`coll + elem`|create new collection that has all elements of coll and elem|
59
+
|`coll - elem`|create new collection that has all elements of coll except elem|
60
+
|`coll ++ elems`|create new collection that has all elements of coll and elems|
61
+
|`coll -- elems`|create new collection that has all elements of coll except elems|
62
+
|`coll :+ elem`|create new collection that has all elements of coll and elem at the end|
63
+
|`elem +: coll`|create new collection that has all elements of coll and elem at the beginning|
64
+
|`immutableColl += elem`<br>`immutableColl -= elem`<br>`immutableColl ++= elems`<br>`immutableColl --= elems`<br>`elem +=: immutableColl`<br>`immutableColl :+= elem|same as the operations without "=", but works only if "immutableColl is a var, not a val. the created collection is assigned to "immutableColl".|
65
+
|`def isEven(i:Int= if (i%2==0) true else false`<br>`val evenNumbers:List[Int] = List(1,2,3,4).filter(isEven)`|scala collections are a major epic win. they have ~100 methods which operate on the data of a collection and there is *absolutely nothing* you cannot do with them.|
66
+
|`val evenNumbers:List[Int] = List(1,2,3,4).filter((i:Int)=> i%2==0)`|same as above, just shorter|
67
+
|`val evenNumbers = List(1,2,3,4).filter(i => i%2==0)`|same as above, just shorter. you can skip the () if there is only one parameter|
68
+
|`val evenNumbers = List(1,2,3,4).filter(_ % 2 == 0)`|same as above, just shorter. you can skip part before "=>" if you use a parameter only once and replace the parameter usage by "_"|
| <spanclass="label success">Good</span> `def f(x: Any) = println(x)`<br> <spanclass="label important">Bad</span> `def f(x) = println(x)`| define function <br> syntax error: need types for every arg. |
@@ -85,7 +125,7 @@ about: Thanks to <a href="http://brenocon.com/">Brendan O'Connor</a>, this cheat
85
125
|`object O extends D { ... }`| define a singleton. (module-like) |
86
126
| `trait T { ... }`<br>`class C extends T { ... }`<br>`class C extends D with T { ... }` | traits.<br>interfaces-with-implementation. no constructor params. [mixin-able]({{ site.baseurl }}/tutorials/tour/mixin-class-composition.html).
87
127
|`trait T1; trait T2`<br>`class C extends T1 with T2`<br>`class C extends D with T1 with T2`| multiple traits. |
88
-
|`class C extends D { override def f = ...}`| must declare method overrides. |
128
+
|`class C extends D { override def f = ...}`| must declare method overrides. |
89
129
|`new java.io.File("f")`| create object. |
90
130
| <spanclass="label important">Bad</span> `new List[Int]`<br> <spanclass="label success">Good</span> `List(1,2,3)`| type error: abstract type<br>instead, convention: callable factory shadowing the type |
0 commit comments