Moshi + Kotlin + Sealed班级 [英] Moshi + Kotlin + SealedClass

查看:147
本文介绍了Moshi + Kotlin + Sealed班级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种使用

sealed class Layer

data class ShapeLayer(var type: LayerType) : Layer
data class TextLayer(var type: LayerType) : Layer
data class ImageLayer(var type: LayerType) : Layer

LayerType只是一些枚举,可用于区分该对象应该具有哪种类型.

LayerType is just some enum which can be used to distinguish which type should this object have.

我想我可以这样添加适配器:

I thought I could add Adapter this way:

class LayerAdapter{
    @FromJson
    fun fromJson(layerJson: LayerJson): Layer {
        return when (layerJson.layerType) {
            LayerType.SHAPE -> PreCompLayer()
            LayerType.SOLID -> SolidLayer()
            LayerType.Text -> TextLayer()
        }
    }
}

其中LayerJson将是具有所有LayerTypes的每个可能字段的对象.

Where LayerJson would be object which has every possible field of all LayerTypes.

现在的问题是:

无法序列化抽象类com.example.models.layers.Layer

Cannot serialize abstract class com.example.models.layers.Layer

我可以尝试使用接口,但是我认为在此使用空接口是不正确的.

I could try to use interface, but I don't think it would be correct to use empty interface in this.

推荐答案

原来,我的代码从一开始就是正确的!

It turned out that my code was actually correct from beginning!

问题出在数据类内部的字段声明中:

Problem was with field declaration inside data Class:

data class LayerContainer(var/val layers: List<Layer>)

它与val一起使用,而与var不一起使用! Kotlin不知何故在下面创建了不同的代码. 这是本部分模型的最终代码:

It works with val, and doesn't work with var! Kotlin somehow creates different code down below. This is my final code for this part of model:

@JvmSuppressWildcards var layers: List<Layer>

这篇关于Moshi + Kotlin + Sealed班级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆