forked from matyb/java-koans
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAboutLambdas.java
More file actions
90 lines (71 loc) · 2.31 KB
/
Copy pathAboutLambdas.java
File metadata and controls
90 lines (71 loc) · 2.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package java8;
import com.sandwich.koan.Koan;
import java.util.function.Function;
import java.util.function.Predicate;
import static com.sandwich.util.Assert.assertEquals;
import static com.sandwich.koan.constant.KoanConstants.__;
public class AboutLambdas {
interface Caps {
public String capitalize(String name);
}
String fieldFoo = "Lambdas";
@Override
public String toString() {
return "CAPS";
}
static String str = "";
//lambda has access to "this"
Caps lambdaField = s -> this.toString();
//lambda has access to object methods
Caps lambdaField2 = s -> toString();
@Koan
public void verySimpleLambda() throws InterruptedException {
Runnable r8 = () -> str = "changed in lambda";
r8.run();
assertEquals(str, __);
}
@Koan
public void simpleLambda() {
Caps caps = (String n) -> {
return n.toUpperCase();
};
String capitalized = caps.capitalize("James");
assertEquals(capitalized, __);
}
@Koan
public void simpleSuccinctLambda() {
//parameter type can be omitted,
//code block braces {} and return statement can be omitted for single statement lambda
//parameter parenthesis can be omitted for single parameter lambda
Caps caps = s -> s.toUpperCase();
String capitalized = caps.capitalize("Arthur");
assertEquals(capitalized, __);
}
@Koan
public void lambdaField() {
assertEquals(lambdaField.capitalize(""), __);
}
@Koan
public void lambdaField2() {
assertEquals(lambdaField2.capitalize(""), __);
}
@Koan
public void effectivelyFinal() {
//final can be omitted like this:
/* final */ String effectivelyFinal = "I'm effectively final";
Caps caps = s -> effectivelyFinal.toUpperCase();
assertEquals(caps.capitalize(effectivelyFinal), __);
}
@Koan
public void methodReference() {
Caps caps = String::toUpperCase;
String capitalized = caps.capitalize("Gosling");
assertEquals(capitalized, __);
}
@Koan
public void thisIsSurroundingClass() {
//"this" in lambda points to surrounding class
Function<String, String> foo = s -> s + this.fieldFoo + s;
assertEquals(foo.apply("|"), __);
}
}