错误:类“X”包含非法最终字段“Y”

问题描述 投票:0回答:2

我使用 Kotlin 数据类与 Realm、Gson 注释来从服务器获取数据。

问题:当我在 Android Studio 中运行项目时,出现以下错误:

Error:Class "VenderConfig" contains illegal final field "name".

我正在学习 Kotlin,所以对此不太了解。

我的

VenderConfig
班级是:

@RealmClass
class VenderConfig(
        @SerializedName("name")
        val name: String? = null,
        @SerializedName("website")
        val wb_url: String? = null,
        @SerializedName("icon")
        val icon: String? = null,
        @SerializedName("logo")
        val logo: String? = null,
        @SerializedName("description")
        val description: String? = null,
        @PrimaryKey
        @SerializedName("id")
        val id: Int? = null
) : RealmObject() {

}

我还尝试了

open
关键字与字段并删除了
data
关键字,但它没有解决问题。

android realm kotlin
2个回答
23
投票

您应该使用

var
关键字来声明可变属性。
val
代表不可变(最终)的。

var name: String? = null
name = "Kotlin" // OK

val immutableName: String? = null
immutableName = "Java" // won't compile, val cannot be reassigned

了解更多信息:属性和字段


0
投票

课程不应该是开放吗? (我也是;)

@Realm-database:realm-java-3.1.0.zip xamples\kotlinExample\src\main\kotlin\io ealm xamples\kotlin\model\Person.kt

    package io.realm.examples.kotlin.model

    import io.realm.RealmList
    import io.realm.RealmObject
    import io.realm.annotations.Ignore
    import io.realm.annotations.PrimaryKey

    // ... 
    // Furthermore, the class and all of the properties
    // must be annotated with open 
    // (Kotlin classes and methods are final by default).
    // 
    open class Person(

    ...

    ) : RealmObject() {
        // The Kotlin compiler generates standard getters and setters.
        // Realm will overload them and code inside them is ignored.
        // So if you prefer you can also just have empty abstract methods.
    }
© www.soinside.com 2019 - 2024. All rights reserved.