Warm-up exercise: What is mystery?
val lst = List("Mary", "had", "a", "little", "lamb")
val mystery = lst.filter(_.length > 3)
return and this{ Type1 arg1, Type2 arg2, ... => stat1, stat2, ..., expr }
{ String a, String b => a.length() - b.length() }
{ String, String => int }invoke to call closure
void sort(String[] a, { String, String => int } comp) {
... if (comp.invoke(a[i], a[j]) < 0) ...
}
button1.addActionListener({ ActionEvent event => textField.setText(...); })
{ ActionEvent => void } closure to
new ActionListener() {
public void actionPerformed(ActionEvent event) { // single method
closure.invoke(event);
}
}
doRead(new FileInputStream("foo.dat"), { InputStream in =>
...
in.read();
...
});
doRead(InputStream in : new FileInputStream("foo.dat")) { // looks like a regular block
...
in.read();
...
}
methodCall(Type1 param1, ...
Typen paramn : expr1, ...
exprm) block
is rewritten to
methodCall(expr1, ... exprm, {
Type1 param1, ... Typen
paramn => block })
import java.util.*;
public class Puzzler {
public static void main(String[] args) {
String[] foo = new String[] { "Mary", "had", "a", "little", "lamb" };
Arrays.sort(foo, { String a, String b => return a.length() - b.length() });
System.out.println(Arrays.toString(foo));
}
}
[a, had, Mary, lamb, little]import java.io.*;
public class Puzzle {
public static void doRead(InputStream in, {InputStream ==> void throws IOException } body) throws IOException {
try { body.invoke(in); } finally { in.close(); }
}
public static void main(String[] args) throws IOException {
doRead(InputStream in : new FileInputStream("Puzzle.java")) {
int c = 0;
while ((c = in.read()) != -1) {
if (c == '*') return;
}
System.out.println("No asterisk");
}
System.out.println("Done");
}
}
DoneNo asterisk, then Donereturn Mean?returnreturn; returns from
enclosing block==> instead of
=>button1.addActionListener(ActionListener(ActionEvent event) { ... });
new and the name of the single methodfinalpublictry (InputStream in = new FileInputStream()) {
. . .
}
finally { in.close(); } in implements Disposableusing in C#