我在我的代码中使用 Kotlin“类型安全构建器”模式:
insteadOf("search", "forest|ground") {
println("Do something.");
}
但是,我也在使用 Kryo 来序列化数据(保存游戏),而 Kryo 不喜欢匿名类型:
call: () -> Unit
所以我不得不引入一个“Do”接口(interface)而不是上述类型。但是现在我的代码看起来丑多了:
insteadOf("search", "forest|ground", object : World.InsteadOf.Do {
override fun invoke() {
println("Do something")
}
})
如何在 Do-interface 中使用简单的 { } - 语法?
编辑:
这里有一些澄清。
我有点困惑(不是新闻)。
实际的 Kryo 错误消息似乎与无参数构造函数有关,但紧接着它说:“这是一个匿名类,默认情况下在 Kryo 中不可序列化。”。
这是完整的错误消息:
Exception in thread "main" com.esotericsoftware.kryo.KryoException: Class cannot be created (missing no-arg constructor): fi.starstuff.rogue.World$insteadOf$1
This is an anonymous class, which is not serializable by default in Kryo. Possible solutions: 1. Remove uses of anonymous classes, including double brace initialization, from the containing class. This is the safest solution, as anonymous classes don't have predictable names for serialization.
2. Register a FieldSerializer for the containing class and call FieldSerializer#setIgnoreSyntheticFields(false) on it. This is not safe but may be sufficient temporarily. Use at your own risk.
Serialization trace:
call (com.mygame.World$InsteadOf)
insteadOfs (com.mygame.World)
at com.esotericsoftware.kryo.Kryo$DefaultInstantiatorStrategy.newInstantiatorOf(Kryo.java:1319)
at com.esotericsoftware.kryo.Kryo.newInstantiator(Kryo.java:1127)
at com.esotericsoftware.kryo.Kryo.newInstance(Kryo.java:1136)
这是替代类:
class InsteadOf {
var verbs: Array<String> = arrayOf()
var nouns: Array<String> = arrayOf()
var where: String = ""
var call: (() -> Unit)? = null
}
最佳答案
您基本上可以接受 () -> Unit
insteadOf
中的函数并将其包装成 Do
正文中的实例:
fun insteadOf(foo: String, bar: String, call: () -> Unit) {
val doInstance = World.InsteadOf.Do(call)
/* use doInstance */
}
用法将与第一个示例中的相同。
或者,提供
Do
与接受 () -> Unit
的工厂函数的接口(interface)并返回 Do
实例。
关于Kotlin 类型安全构建器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52274453/