gpt4 book ai didi

scala - @transient 惰性 val 字段序列化

转载 作者:行者123 更新时间:2023-12-04 02:13:35 26 4
gpt4 key购买 nike

我在 Scala 上有问题。我用 @transient lazy val 序列化了一个类的实例 field 。然后我反序列化它,该字段被分配null .我期待反序列化后的惰性评估。我该怎么办?

以下是示例代码。

object Test {

def main(args: Array[String]){

//----------------
// ClassA - with @transient
//----------------

val objA1 = ClassA("world");

println(objA1);
// This works as expected as follows:
// "Good morning."
// "Hello, world"

saveObject("testA.dat", objA1);

val objA2 = loadObject("testA.dat").asInstanceOf[ClassA];

println(objA2);
// I expect this will work as follows:
// "Good morning."
// "Hello, world"
// but actually it works as follows:
// "null"



//----------------
// ClassB - without @transient
// this works as expected
//----------------

val objB1 = ClassB("world");

println(objB1);
// This works as expected as follows:
// "Good morning."
// "Hello, world"

saveObject("testB.dat", objB1);

val objB2 = loadObject("testB.dat").asInstanceOf[ClassB];

println(objB2);
// This works as expected as follows:
// "Hello, world"

}

case class ClassA(name: String){

@transient private lazy val msg = {
println("Good morning.");
"Hello, " + name;
}

override def toString = msg;

}

case class ClassB(name: String){

private lazy val msg = {
println("Good morning.");
"Hello, " + name;
}

override def toString = msg;

}

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

def saveObject(fname: String, obj: AnyRef){
val fop = new FileOutputStream(fname);
val oop = new ObjectOutputStream(fop);
try {
oop.writeObject(obj);
} finally {
oop.close();
}
}

def loadObject(fname: String): AnyRef = {
val fip = new FileInputStream(fname);
val oip = new ObjectInputStream(fip);
try {
oip.readObject();
} finally {
oip.close();
}
}

}

最佳答案

在 Scala 的 Trac 中有几张票:

  • 1573
  • 1574

  • 我建议您针对 2.9 的主干版本进行测试,因为它可能已经修复。

    关于scala - @transient 惰性 val 字段序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4772825/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com