Kotlin 类型安全构建器

标签 kotlin

我在我的代码中使用 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/

相关文章:

android - 如何在 Jetpack Compose 的 OutlinedTextField 中显示错误消息

android - flutter 平台 View : Trying to create a platform view of unregistered type

spring-boot - 如何使用测试容器将 selenium 容器连接到 localhost 网络?

kotlin - 错误 : cannot find symbol import com. gourav.news.databinding.ActivityDetailBindingImpl;

java - Android 循环调用 Rest API

用 kotlin 和 React Native 应用程序编写的 Android Native 应用程序

Java 到 Kotlin 转换器和可为空的方法参数

java - 从 Java 调用 Kotlin 高阶函数

kotlin - 如何在Kotlin中替换长链的forEach {}语句?

android - Kotlin:将两个不同的列表合并为一个,并从两个列表中选择数据