错误:包含非法的最终字段-Kotlin

时间:2017-07-13 06:58:51

标签: android realm kotlin

我正在使用带有Realm,Gson注释的Kotlin数据类来从服务器获取数据。

问题:当我在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() {

}

我也尝试使用字段打开关键字并删除数据关键字,但它没有解决问题。

2 个答案:

答案 0 :(得分:9)

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

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

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

有关详细信息:Properties and Fields

请注意,我不熟悉Realm,这可能无法解决您的问题。

答案 1 :(得分:0)

班级不应该打开吗? (我也是;)

@ Realm-database:realm-java-3.1.0.zip \例子\ kotlinExample \ SRC \主\科特林\ IO \境界\例子\科特林\模型\ 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.
    }