【问题标题】:Not getting a variable name using class instance: Kotlin没有使用类实例获取变量名:Kotlin
【发布时间】:2020-11-03 17:42:57
【问题描述】:

我正在关注有关 LiveData 和 ViewModel 的旧教程。这些是链接。

  1. [https://www.youtube.com/watch?v=d7UxPYxgBoA][1]
  2. [https://resocoder.com/2018/09/07/mvvm-on-android-crash-course-kotlin-android-architecture-components/]

在启动 FakeDatabase 类并获取它的变量时,我在 InjectUtil.kt 类中遇到错误。我正在学习教程,但不知道为什么会得到它。

//InjectUtil Object
package dk.humma.livedata_viewmodel.utilities

import dk.humma.livedata_viewmodel.data.FakeDataBase
import dk.humma.livedata_viewmodel.data.QuotesRepository
import dk.humma.livedata_viewmodel.ui.quotes.QuotesViewModelFactory

// Finally a singleton which doesn't need anything passed to the constructor
object InjectorUtils {
    // This will be called from QuotesActivity
    fun provideQuotesViewModelFactory(): QuotesViewModelFactory {
        // The whole dependency tree is constructed right here, in one place
        val quoteRepository = QuotesRepository.getInstance(FakeDataBase.getInstance().quoteDao) 
        //Getting error while trying to get quoteDao variable
        // Not accessing quoteDao
        return QuotesViewModelFactory(quoteRepository)
    }
}

//FakeDataBase class
package dk.humma.livedata_viewmodel.data

class FakeDataBase private constructor(){

    var quoteDao = DataTable()
    private set

    companion object {
        @Volatile private var instance : FakeDataBase? = null

        fun getInstance() {
            instance?: synchronized(this){
                instance?: FakeDataBase().also { instance = it }
            }
        }
    }
}

有人知道吗?非常感谢。

【问题讨论】:

  • 是编译错误还是运行时错误?如果是运行时错误/异常,请发布整个堆栈跟踪。
  • 请发布错误以解决问题。
  • 这里没有访问 quoteDao 变量。 val quoteRepository = QuotesRepository.getInstance(FakeDataBase.getInstance().quoteDao) //我没有得到quoteDao。我只是写在这里,但在 IDE 中它说,未解决的参考:quoteDao

标签: android kotlin android-livedata android-viewmodel android-mvvm


【解决方案1】:

您的 getInstance 函数没有返回任何内容 - 如果您查看该函数的文档弹出窗口,它的返回类型将为 Unit。而Unit 没有quoteDao 属性,这就是IDE 抱怨的原因。如果您遇到类似的错误,请检查您尝试访问它的变量的类型

您可以通过添加return 来修复它(并在它抱怨时添加类型)

fun getInstance() : FakeDataBase {
    return instance?: synchronized(this){
        instance?: FakeDataBase().also { instance = it }
    }
}

或作为表达式(= 而不是需要return 的功能块)

fun getInstance() = instance?: synchronized(this) {
    instance?: FakeDataBase().also { instance = it }
}

【讨论】:

  • 现在我在 InjectUtils 对象中遇到另一个错误。错误是将主构造函数类 'QuotesViewModelFactory' 的参数 'quoteRespiratory' 类型更改为 'unit'。 "
  • 我看不到课程,但我猜你需要为QuotesRepository.getInstance() 做同样的事情 - 它抱怨那个调用的结果(quoteRepository,你是传入QuotesViewModelFactory 构造函数)的类型为Unit。这意味着 getInstance 正在返回 Unit (这是 Kotlin 中的“无返回类型”实际返回类型)。您可能只是不再返回实例
猜你喜欢
  • 1970-01-01
  • 2012-03-18
  • 1970-01-01
  • 1970-01-01
  • 2013-03-30
  • 2014-06-15
  • 1970-01-01
  • 2021-03-28
  • 1970-01-01
相关资源
最近更新 更多