blob: 8d7e1be5572cbfe465b11bcb3fe8d581635c3442 (
plain) (
blame)
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
|
class C {
def methodLift1 = {
def isEven(c: Int) = c % 2 == 0
val f: Int => Boolean = isEven
f
}
def methodLift2 = {
def isEven(c: Int) = c % 2 == 0
def isEven0(c: Int) = isEven(c)
val f: Int => Boolean = isEven0
f
}
def methodLift3 = {
def isEven(c: Int) = {toString; c % 2 == 0}
def isEven0(c: Int) = isEven(c)
val f: Int => Boolean = isEven0
f
}
}
object Test {
def main(args: Array[String]): Unit = {
val c = new C
{
val f = c.methodLift1
assert(f(0))
assert(!f(1))
val f1 = serializeDeserialize(f)
assert(f1(0))
assert(!f1(1))
}
{
val f = c.methodLift2
assert(f(0))
assert(!f(1))
val f1 = serializeDeserialize(f)
assert(f1(0))
assert(!f1(1))
}
{
val f = c.methodLift3
assert(f(0))
assert(!f(1))
try {
serializeDeserialize(this)
assert(false)
} catch {
case _: java.io.NotSerializableException =>
// expected, the closure in methodLift3 must capture C which is not serializable
}
}
}
def serializeDeserialize[T <: AnyRef](obj: T): T = {
import java.io._
val buffer = new ByteArrayOutputStream
val out = new ObjectOutputStream(buffer)
out.writeObject(obj)
val in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray))
in.readObject.asInstanceOf[T]
}
}
|