繁体   English   中英

在 Kotlin 数据类中调用超类构造函数之前的访问函数

[英]Access function before calling superclass constructor in Kotlin data class

我在 Kotlin 中使用数据类来显着减少我必须编写的 Java 代码量。

但是,在我的一个 Java 类中,我不确定如何在 Kotlin 中实现相同的结果。

我的 Java 类看起来有点像这样:

public class DataObject {

    private int mId;
    private String mName;

    public DataObject(int id, String name) {
        mId = id;
        mName = name;
    }

    public DataObject(Context context, int id) {
        mId = id;
        Cursor cursor = ...
        cursor.moveToFirst();
        mName = cursor.getString(...);
        cursor.close();
    }

    public int getId() {
        return mId;
    }

    public String getName() {
        return mName;
    }

}

我试图用 Kotlin 重写它,到目前为止我有这个:

data class DataObject(val id: Int, val name: String) {

    constructor(context: Context, id: Int) : this(id, fetchName(context))

    private fun fetchName(context: Context): String {
        val cursor = ...
        cursor.moveToFirst()
        val name = cursor.getString(...)
        cursor.close()
        return name
    }

}

但是我的 IDE (Android Studio fetchName(context)在我的constructor fetchName(context)红色强调了我调用fetchName(context)的部分。 它显示以下消息:

在调用超类构造函数之前无法访问fetchName

我应该如何解决这个问题?

您只能在完全构造的对象上使用成员函数。 解决这个问题的一种方法是使用私有扩展函数或简单的函数来获取名称:

private fun Context.fetchName(): String {
    ///...
    return cursor.getString(1)
}

data class DataObject(val id: Int, val name: String) {
    constructor(context: Context, id: Int) : this(id, context.fetchName())
}

虽然我确实认为使用Cursorconstructor有点太繁重了。 我会像这样使用单独的Factory

data class DataObject(val id: Int, val name: String) {
    object FromCursorFactory {
        fun create(id: Int, context: Context): DataObject {
            val name = context.fetchName()
            return DataObject(id, name)
        }
    }
}

进一步阅读:

另一种方法是使用伴随对象。 这也将允许您在数据类之外调用该函数(在您的特定情况下可能没有用)

data class DataObject(val id: Int, val name: String) {

  constructor(context: Context, id: Int) : this(id, fetchName(context))

  companion object {

    fun fetchName(context: Context): String {
      val cursor = ...
      ...
      return name
    }
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM