【问题标题】:Error: Contains illegal final field -Kotlin错误:包含非法的最终字段 -Kotlin
【发布时间】:2017-07-13 06:58:50
【问题描述】:

我正在使用带有 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() {

}

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

【问题讨论】:

  • 课程不应该是open 才能正常工作吗?

标签: android realm kotlin


【解决方案1】:

您应该使用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,这可能无法解决您的问题。

【讨论】:

    【解决方案2】:

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

    @Realm-数据库:realm-java-3.1.0.zip \examples\kotlinExample\src\main\kotlin\io\realm\examples\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.
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-04
      • 2021-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多